SoFunction
Updated on 2024-10-29

Python collection addition, deletion, and modification operations

Preface:

Set is divided into two kinds of variable and immutable set, so its add, delete, change and check operation depends on the type of set to decide. Immutable data of course can not be added, deleted or changed, only query, variable collection is slightly less restrictive. In addition to the collection is not required, so there is no way to query directly through the subscripts, while the collection of elements do not have their own key, you can not use the key to query, then how to operate the collection of this data type? The following gives you a list of some of the methods of operation.

1. Collections add new set elements

set1 = {'name', 19, 'python'}
('abc')  # Variable sets, direct modification of the original set
print(set1, type(set1))

Returns results:

{'python', 'name', 19, 'abc'} <class 'set'>

2. Delete variable set elements

('python')  # Delete the specified element, if not, return an error
print(set1)
('name')  # Delete the specified element, if not, return to the original collection
print(set1)
()  # Randomly remove a variable set element because the set is unordered
print(set1)
()  # Empty all elements of the mutable collection
print(set1)
del set1  # Clear the collection
print(set1)

Returns results:

{'name', 19, 'abc'}
{19, 'abc'}
{'abc'}
set()
NameError: name 'set1' is not defined

3. Modifying variable collections

Collection elements are immutable types, so they cannot be modified

4. Collection element query method

Collections cannot be queried by means of key-value pairs and are also unordered without subscripts, so they cannot be queried, only traversed.

for i in set1:
    print(i)
# Accessed through iterators
its = iter(set1)  # Generate an iterator
print(next(its))  # Access via next()
# or traversing iterators via for in
for i in its:
print(i)
# Immutable and mutable collections are the same traversal operations

To this article on the Python collection of add, delete and check the operation of the article is introduced to this, more related to the Python collection of add, delete and check the contents of the search for my previous posts or continue to browse the relevant articles below I hope that you will support me in the future more!