1 Adding elements in a list
(1) using + by a=a+[...]
Note that using + means two things: adding elements to the existing list and make a copy of it.
(2)using append by a.append(…)
This means just adding elements to the existing list(end).
(3)using extend by a.extend(…)
It can only be used when adding a list to the existing list.
(4)using insert by a.insert(a, …)
Insert can adding some elements to the ath place of the existing list.
a = [1,2,3]
a = a + [4]
print(a)#[1, 2, 3, 4]
a.append(5)
print(a)#[1, 2, 3, 4, 5]
a.extend([6,7])
print(a)#[1, 2, 3, 4, 5, 6, 7]
a.insert(0,8)
print(a)#[8, 1, 2, 3, 4, 5, 6, 7]
a.append([9,10])
print(a)#[8, 1, 2, 3, 4, 5, 6, 7, [9, 10]]
2. Deleting elements in a list
(1) using del by del a[…]
delete the element of a fixed index.
(2)using pop by a.pop(…)
If without parameter, it means deleting the last element. Otherwise, it means delete the given index, like del.
(3) using remove(…) by a.remove(…)
remove the fixed content of a list
del a[0]
print(a)#[1, 2, 3, 4, 5, 6, 7, [9, 10]]
a.pop()
print(a)#[1, 2, 3, 4, 5, 6, 7]
a.pop(0)
print(a)#[2, 3, 4, 5, 6, 7]
a.remove(3)
print(a)#[2, 4, 5, 6, 7]
3. Adding elements in a set
(1) using add by b.add(…)
Adding elements into a
(2) using update by b.update(…)
Can be used only when adding a set or a list
b = {1,2}
b.add(3)
print(b)#{1, 2, 3}
b.add(1)
print(b)#{1, 2, 3}
b.update({4,5})
print(b)#{1, 2, 3, 4, 5}
b.update({6},{7,8})
print(b)#{1, 2, 3, 4, 5, 6, 7, 8}
b.update([9,10])
print(b){1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
4. Deleting elements in a set
(1) using discard by b.discard(…)
Delete a fixed element in or not in the set.
(2) using remove by b.remove(…)
Can be just to delete the existing element in the set.
(3) using pop by b.pop(…)
Since set is with no order, it delete one element randomly.
(4) using clear by b.clear()
Delete all elements in the set
b.discard(1)
print(b)#{2, 3, 4, 5, 6, 7, 8, 9, 10}
b.discard(11)
print(b)#{2, 3, 4, 5, 6, 7, 8, 9, 10}
b.remove(2)
print(b)#{3, 4, 5, 6, 7, 8, 9, 10}
b.pop()
print(b)#{4, 5, 6, 7, 8, 9, 10}
b.clear()
print(b)#set()
本文详细介绍了Python中列表和集合的基本操作,包括添加、删除元素的方法,并提供了实例演示。
913

被折叠的 条评论
为什么被折叠?



