[Python] study notes 2

Supplement to last time: If the sorting does not want to change the original list, you can define a new one.

x = [3, 7, 2, 11, 8, 10, 4]
new_list=sorted(x)
print(x)
print(new_list)

Results:
Insert picture description here
1. Add and delete to the list

x = [3, 7, 2, 11, 8, 10, 4]
print(x)
x.append(12)#在末尾加元素
print(x)
x.remove(3)#移走值为3的元素
print(x)
print(x.pop(3))#删除指定位置的对象,且输出看看删除的是哪个
print(x)

Result:
Insert picture description here
2. Consolidate the list
Extend the list by adding at the end.
And the types of elements in a list can be different.

x = [3, 7, 2, 11, 8, 10, 4]
y=['Steve', 'Rachel', 'Monica', 'Michael', 'Lester', 'Jessica', 'Adam']
x.extend([6,5])#末尾续加这个列表
print(x)
print('x+y: ',x+y)

Result:
Insert picture description here
3. Insert the object before the specified position in the list

x = [3, 7, 2, 11, 8, 10, 4]
x.insert(4,[4,5])#在指针4前加入这个对象
print(x)

result:
Insert picture description here

x = [3, 7, 2, 11, 8, 10, 4]
x.insert(4,1111)#在指针4前加入这个对象
print(x)

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/Shadownow/article/details/105815487