Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. This article focuses on collections (sets and frozensets) of Python data types. Let’s go through collections at a time. Dry goods full, suggested collection, need to use often look. If you have any questions or need, you are welcome to send me a message.

What is a set?

What is a set? For those of you who haven’t even used the collection data type. I must have heard the term set in my math class. A set is a basic concept in mathematics, which means that a set can be formed by a bunch of numbers that are not repeated. Going back to the data types of collections in Python, it can be used to hold multiple data that are not repeated and whose data types are immutable. These immutable types include numbers, strings, and tuples. That is, mutable data types such as lists and dictionaries cannot be used as elements of collections. Collections in Python are divided into sets of type set and fronzenset. The difference between these two types of collections is that a set is mutable, that is, it can add or remove elements inside the set, while a fronzenset is immutable. That is, you cannot add or delete elements inside the collection. The set collection is defined as {element1,element2… ,elementn}, where, element1~elementn represents the elements in the set, and the number is unlimited. Each element is unique.

How do I use set?

Create a set

There are two ways to create a set. The first way is to create a set with {} syntax: {element1,element2… The syntax of set(iterable) is set(iterable), where an empty set object is created if iterable is not passed. The passed iterable must be a sequence that can be iterated over, such as strings, lists, etc. Here’s an example:

set_demo = {'1'.2, (Farmers' of '.'flying elder brother')}
print(set_demo)
list = [1.'test'.1, (Farmers' of '.'flying elder brother')]
print(List result ='.list)
set_demo1 = set(list)
print('Set result =', set_demo1)
Copy the code

The results are as follows:

{2, (farmers' of ', 'flying elder brother'), '1'} result list = [1, 1 'test', (farmers' of ', 'flying elder brother')] generating set results = {1, (farmers' of ', 'flying elder brother'), 'test'}Copy the code

You can see that even though there are two 1’s in the list, there will still be only one 1 after the set is generated, meaning that elements with the same value in the set will only be stored once.

Delete set set

Deleting a set can be done by using the del(setName) function. Setname is the name of the set to be deleted.

Access the set collection element

Since the elements in a collection are unordered, the spiciness accesses the elements using subscripts like a list. In Python, the most common way to access collection elements is to use a loop that reads the elements out of the collection one by one.

set_demo = {'1'.2, (Farmers' of '.'flying elder brother')}
for value in set_demo:
    print(value)
Copy the code

The results are as follows:

2 (' yard farmer ', 'fly brother ') 1Copy the code

The output of the element is also unordered.

Deletes elements from the collection

There are two ways to remove elements from a collection: first, by using the remove() method, which has the syntax: Remove (Element), where setName is the set to be operated and Element is the element to be deleted. If the deletion fails, a KeyError will be reported. The second method: discard(), which uses the same method as remove(), except that no error is reported if removing elements fails.

set_demo = {'1'.2, (Farmers' of '.'flying elder brother')}
set_demo.remove('1')
print('Set after deleting element 1 =', set_demo)
set_demo.discard('5')
print('Set after deleting element 5 =', set_demo)
Copy the code

The results are as follows:

After removing elements 1 set = {2, (farmers' of ', 'flying elder brother')} after removing elements 5 set = {2, (farmers' of ', 'flying elder brother')}Copy the code

Adds elements to the collection

Add (Element), where setName is the set to be operated on and Element is the element to be added. Only immutable elements can be added, for example: Numbers, tuples, or strings cannot be added to mutable data such as lists, dictionaries, and sets. Here’s an example:

set_demo.add('6')
print('Add element 6 and the result is ='., set_demo)
Copy the code

The results are as follows:

The result of adding element 6 is = {2, '6', (' mynong ', 'flybrother ')}Copy the code

The intersection and complement of a set

In mathematics, sets have intersection unions and complements. Collections in Python have these concepts as well.

intersection

A new set is generated by concatenating two sets by &, which takes the elements common to both sets.

And set

Through | connecting two set set can generate a new set, a new collection to take two all elements of the original collection.

Difference set

A new set is generated by concatenating two sets of sets, taking elements that are in one set and not in the other. Here’s an example:

set_demo = {1.3.5.6}
set_demo1 = {2.4.6}
print("Take the result of intersection =", set_demo & set_demo1)
print("The result of taking the union =", set_demo | set_demo1)
print("The result of taking the difference set =", set_demo - set_demo1)
Copy the code

The run result is

Intersection result = {6} Union result = {1, 2, 3, 4, 5, 6} Difference result = {1, 3, 5}Copy the code

Other methods in set

Dir (set) allows you to view all the methods in the set collection. There are the following methods:

['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

Copy the code

The method of naming more standard, according to the English name can guess the role of the method, here is not to repeat the meaning of each method. Here are some direct examples:

set_demo = {1.3.5.6}
set_demo1 = {2.4.6}
set_demo.update({12, (2.3)})
print('set_demo after calling the update method ', set_demo)
set_demo = {1.3.5.6}
print('Set_demo after calling the union method', set_demo.union(set_demo1))
print('set_demo after calling the difference method ', set_demo.difference(set_demo1))
print('Set_demo after calling the __sub__ method', set_demo.__sub__(set_demo1))
Copy the code

The results are as follows:

After set_demo calls the update method {1, 3, (2, 3), 5, 6, 12} set_demo calls the union method {1, 2, 3, 4, 5, 6} set_demo calls the difference method {1, 3, 5} set_demo after calling __sub__ method {1, 3, 5}Copy the code

Frozenset collection

A Frozenset is an immutable version of a set. In contrast to a set, the elements in a Frozenset are immutable, that is, there is no way to add or remove elements. The way to create a frozenset collection is through the frozenSet () method. The syntax is frozenset(iterable), where an empty set object is created if iterable is not passed. The passed iterable must be a sequence that can be iterated over, such as strings, lists, etc.

frozenset_demo = frozenset(list)
print("Frozenset_demo is of type =".type(frozenset_demo))
print("Result of frozenset_demo =", frozenset_demo)
Copy the code

The results are as follows:

Frozenset_demo is of type = <class 'frozenset'> frozenset_demo result = frozenset({(' code ', 'fly '), 1, 'test'})Copy the code

conclusion

This article introduces the basic concepts and detailed usage of sets in Python.

Good article recommendation

Dict lets anyone find their partner (key/value pairs). Python’s built-in data types — lists and tuples — are available in 10 chapters (5) Python built-in data types – sequences and strings, no girlfriend, not nanny, just use dry stuff What are the built-in data types in Python? Just to get a sense of the numbers

I am Mynongfei and thank you again for reading this article. The whole network with the same name [code nongfei brother]. Thank you again for reading this article.