How to implement the operation of adding, deleting, changing and searching in Python collection
This article mainly describes how Python collection to achieve add, delete and check operations, the article is very detailed, has a certain reference value, interested friends must read!
1. Set new set element set1 = {'name', 19, 'python'}set1.add ('abc') #Variable set, directly modify the original set print(set1, type(set1))
Return Results:
{'python', 'name', 19, 'abc'}
2. set1.remove ('python ') #removes specified element, if not, returns error print(set1)set1.discard ('name') #removes specified element, if not, returns original set print(set1)set1.pop() #randomly removes a variable set element because the set is out of order print(set1)set1.clear() #empties all elements in variable set print(set 1)del set1 #clears set print(set1)
Return Results:
{'name', 19, 'abc'}
{19, 'abc'}
{'abc'}
set()
NameError: name 'set1' is not defined
3. Modify variable sets
Collection elements are immutable types, so they cannot be modified
4. Collection element query method
Collections cannot be queried by key-value pairs, and they are also unordered without subscripts, so they cannot be queried and can only be traversed.
for i in set1: print(i)#accessing its = iter(set1) #generating iterators print(next(its)) #accessing via next()#or traversing iterators for i in its:print(i)#invariant sets and variable sets are the same traversal operations The above is "Python sets how to achieve add, delete and change search operations" All the contents of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!