description:
A set is an unordered sequence of non-repeating elements. Sets and lists are very similar
The difference between sets and lists:
- Only immutable objects can be stored in the collection
- The objects stored in the collection are unordered (not stored in the order in which the elements are inserted)
- Duplicate elements cannot and will not appear in the collection
Create a collection:
You can use braces {} or set() to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.
Method 1: Use {} to create a collection
s = {
10,3,5,1,2,1,2,3,1,1,1,1}
print(s) # {1, 2, 3, 5, 10}
print(type(s)) # <class 'set'>
As can be seen from the code above, the objects stored in the collection are unordered, and there will be no duplicate elements (can be used for deduplication)
集合中只能存储不可变对象
a = {
[1,2,3],[4,6,7]}
print(a) # 报错 TypeError: unhashable type: 'list'
Method 2: Use the set() function to create a collection
创建一个空集合
s = set()
print(s) # set()
print(type(s)) # <class 'set'>
Use set() to convert sequences and dictionaries to sets. When using set() to convert dictionaries to sets, only the keys in the dictionary are included
s = set([1,3,4,4,5,1,1,2,3,4,5])
print(s) # {1, 2, 3, 4, 5}
s = set('hello')
print(s) # {'h', 'o', 'l', 'e'}
s = set({
'a':1,'b':2,'c':3})
print(s) # {'a', 'c', 'b'}
The use of sets:
- Use in and not in to check the elements in the collection
s = {
'a','b',1,2,3,1}
print('c' in s) # False
print(1 in s) # True
print(2 not in s) # False
- Use len() to get the number of elements in the collection
s = {
'a','b',1,2,3,1}
print(s) # {1, 2, 3, 'a', 'b'}
print(len(s)) # 5
- add() adds an element to the collection. If the element already exists, no operation is performed.
s = {
'a','b',1,2,3,1}
s.add(3)
s.add(10)
s.add('hello')
print(s) # {1, 2, 3, 10, 'hello', 'b', 'a'}
- update() adds the elements in a collection to the current collection, update() can pass a sequence or a dictionary as a parameter, and the dictionary only uses keys
s1 = {
1,2,3}
s2 = set("hello")
print(s2) # {'l', 'o', 'e', 'h'}
s1.update(s2) # 将一个集合中的元素添加到当前集合中
print(s1) # {'h', 1, 2, 3, 'e', 'o', 'l'}
s1 = {
1,2,3}
s1.update((10,20,30,40)) # 传递一个序列作为参数
print(s1) # {1, 2, 3, 40, 10, 20, 30}
s1 = {
1,2,3}
s1.update({
100:'aa',200:'bb',300:'cc',400:'dd'}) # 传递一个字典作为参数
print(s1) # {400, 1, 2, 3, 100, 200, 300}
- pop() randomly delete an element in the set and return
s = {
4, 2, 3, 100, 40, 'o', 'a', 'h',}
result = s.pop()
print(result) # 2
- remove(x) delete the specified element x in the collection
s = {
4, 2, 3, 100, 40, 'o', 'a', 'h',}
s.remove(100)
print(s) # {2, 3, 4, 'h', 40, 'o', 'a'}
- clear() clear the collection
s = {
4, 2, 3, 100, 40, 'o', 'a', 'h',}
s.clear()
print(s) # set() 空集合