Sets

In mathematics, there is such a thing as a set (or set theory). Perhaps you even studied them in a math course. You may even be familiar with Venn diagrams.
In practice, a set can be thought of simply as a well-defined set of individual objects, called elements or members.
Grouping objects into a set can be useful in programming, and Python provides us with the built-in type set.

Sets (type set) differ from other types of objects in the unique operations that can be performed on them.

The built-in type set in Python has the following characteristics:
    The
  • elements of a set are unordered (meaning that two sets are equivalent if they contain the same elements). The elements of the set are stored not sequentially, but according to certain algorithms that allow you to quickly determine whether an element belongs to a set (without enumeration of all elements);
  • set elements are unique. Duplicate elements are not allowed;
  • sets are mutable (for example, you can add an element to a set), but the elements themselves inside the set must be immutable (numbers, strings, tuples). You cannot make a list or another set an element of a set;

 

Create set
1 way

Simply enumerate in curly braces the elements in the set.

x = {"school", "teacher", "class", student}
 

2 way 
Use the built-in function set(). x = set()    # empty set list_name = ["Andry", "Bob", "Caroline"] y = set(list_name)    # you can create multiple                        # from any iterable object z = set(["Andry", "Bob", "Caroline"])     # {'Bob', 'Caroline', 'Andry'} k = set(("Andry", "Bob", "Caroline"))     # {'Bob', 'Caroline', 'Andry'} s = "string s" m = set(s)    # {'i', 't', 'g', 'r', 'n', & #39;s', ' '} -                # Pay attention!                # the order of the elements can be any,               # elements are not repeated n = {42, 'foo', 3.14159, None, (1, 2, 3)}    # elements in                                                # can be of different types  
Set output
The elements of the set are displayed in an arbitrary order, not necessarily in the order in which they are added. z = set(["Andry", "Bob", "Caroline"])  print(z)     # {'Bob', 'Caroline', 'Andry'} print(*z)    # Bob Andry Caroline

Methods for working with sets


Number of elements in the set
The len() method returns the number of elements in the set. k = {42, 'foo', 3.14159, None, (1, 2, 3)}  print(len(k))    #5

 

Determining if an element is in a set (membership in)
k = {42, 'foo', 3.14159, None, (1, 2, 3)}  print(42 in k)    # True print(2 in k)     # False
Although the elements contained in a set must be of an immutable type, the sets themselves can be changed. 

 

Adding an element to set
x.add(<elem>)
to the set  x adds <elem> which must be the only immutable object.

 

Removing an element from a set
1) x.remove(<elem>)
<elem>  is removed from the x set. Python throws an exception (error) if <elem> is not in x.

2) x.discard(<elem>)
the same deletes, but in case of absence of an element in the set, it does not raise an exception.

3) x.pop()
removes and returns a random element from the set. If the set is initially empty, then an exception (error) occurs.

4) x.clear()
removes all elements from the set (clears the set).

Error

Set sorting?

As we know, the order of the elements in the set is not taken into account. So does it make sense to talk about sorting sets in Python 3?! (That's why there's a question mark in the title)

To quickly find an element in a set, it is desirable to store them in memory in an ordered form.

Let's look at some examples. What happens to elements of different data types in the same set? Such elements should not be sorted. If we print elements using the print() command, they will be output like this:

a = {0, 1, 12, 'b', 'ab', 3, 2, 'a'} print(a) # {0, 1, 2, 3, 'a', 12, 'b', 'ab'} In this case, unsorted values ​​are displayed. If you repeat the launch, then the output order may be different. But this is only if elements of different types are mixed.

Let's try to display data of one type (for example, only numbers): a = {0, 1, 12, 3, 2} print(a) # {0, 1, 2, 3, 12} All elements are displayed in order. Let's try to convert it to a list: a = {0, 1, 12, 3, 2} b = list(a) print(b) # [0, 1, 2, 3, 12] Similarly, the elements sorted in ascending order were written to the list.

It turns out that elements are stored in memory in an ordered form if they are of the same type. But it's better not to count on it, Python algorithms can change.

If you need to get a sorted list from a set, it's better to use the sort (sorted) function to be sure ). The elements will be exactly sorted. Your code will be understandable to others.