Python array elements add, modify and delete

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43264177/article/details/82895753

Array
An array is an orderly collection, you can add and remove elements which at any time.

Array definition

student=['jack','Bob','Harry','Micle']
print(student)

Here Insert Picture Description

Access array elements
with an index to access the list of elements in each position, remember that the index is zero-based:

student=['jack','Bob','Harry','Micle']
print(student)

print(student[0])
print(student[3])
print(student[-1]) #访问最后一个元素

Here Insert Picture Description

Note: When the index is out of range, Python will report a IndexError mistake, therefore, to ensure that the index not out of bounds.
For example: print (student [4] will report the following error:
Here Insert Picture Description
add elements

#末尾添加元素
student.append('51zxw')
print(student)

Here Insert Picture Description

#指定位置添加元素
student.insert(0,'hello')
print(student)

Here Insert Picture Description

Modify elements

#将hello的值变成NO.1
student[0]='NO.1'
print(student)

Here Insert Picture Description

Removing elements

#删除末尾元素
student.pop()
print(student)

Here Insert Picture Description

#删除指定位置元素
student.pop(1)
print(student)

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_43264177/article/details/82895753