[python] Adding or Deleting elements in a list or set

本文详细介绍了Python中列表和集合的基本操作,包括添加、删除元素的方法,并提供了实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值