# Sets in Python

A set in the Python programming language is an unordered set of unique values. The elements of this dataset can be any immutable objects, such as numbers, symbols, or strings. Unlike arrays and lists, the order of values is not taken into account when processing its contents. A number of operations can be performed on one as well as several sets, thanks to the functions of the standard Python programming language library.

## Creating

Before you start working with a set, you first need to create it. You can do this by simply assigning a sequence of values to a variable, highlighting them with curly braces. The following example shows code that creates a set of integers named a, then prints its contents.

```a = {1, 2, 0, 1, 3, 2}
print(a)

{0, 1, 2, 3}```

As you can see, all the elements of the resulting sequence are unique, with no repetitions. There is another way to create sets, which involves using the set method. An argument of this function can be a set of some data or even a string of text, as shown in the following example.

```a = set('data')
print(a)

{'d', 'a', 't'}```

As a result of executing this code, the program fills the new set with unique characters from the input string. The contents of the set are also displayed.

## Using

Typically used for the following operations:

• Check if the given value is in the set. For this purpose in is used.
`a = {0, 1, 2, 3}print(2 in a)True`
• The reverse is a check for absence. This is used not in.
`a = {0, 1, 2, 3}print(2 not in a)False`
• Try all elements.
`for a in {0, 1, 2}:    print(a)012`

## Generator

To create a set, you can use a generator in Python that allows you to fill lists, as well as other datasets, with some conditions. Filling is done similarly to generating lists, discussed in a separate article. The following code demonstrates the generation of a with a for loop for several numbers.

```a = {i for i in [1, 2, 0, 1, 3, 2]}
print(a)

{0, 1, 2, 3}```

As before, the print method shows the contents of the resulting set of values, where there are no repetitions, because identical numbers are automatically removed.

## Changing sets

To manipulate the content of sets, the Python language has special methods that allow you to add and remove individual elements.

### Getting the size

To find out the exact number of elements in a set, use the method len, which takes a dataset as an argument. The function print will print the result.

```a = {0, 1, 2, 3}
print(len(a))

4```

To add new values, you need to call the add method. The argument in this case is the sequence element to be added. In the Python code example, add an element with value 4 to the set.

```a = {0, 1, 2, 3}
print(a)

{0, 1, 2, 3, 4}```

### Deleting an element

The following functions are used in Python to remove elements from a set (except for purge, which will be discussed below):

• remove – remove element with exception generation if there is no such element;
• discard – remove element without exception generation, if element is absent;
• pop – removal of the first element, an exception is generated when trying to remove from an empty set.

Get rid of unnecessary values in the data set with remove. The input parameter here is the element to remove (in the example, we remove the number with value 3).

```a = {0, 1, 2, 3}
a.remove(3)
print(a)

{0, 1, 2}```

Regarding the pop function, I would like to point out that since the sets are unordered, the random element that is first in memory will be removed. But if they are stored in memory in sorted form, which is not the case, most likely the element with the lowest value will be removed. But don’t count on that.

### Complete cleaning

Sometimes it is necessary to remove all elements completely. To avoid removing each item individually, the clear method, which does not take arguments, is used. If you print the content after clearing, only the name of the element will be shown.

```a = {0, 1, 2, 3}
a.clear()
print(a)

set()```

As a result, we have an empty set.

## Sorting

The order of elements is not taken into account. So there is no point in talking about sorting sets in Python 3. But on the other hand this is not the case with everything. In order to find an item quickly, it is desirable to keep them in memory in an ordered form. First, consider what happens to elements of different data types in the same set. Such items should not be sorted. If we print the elements, they will be printed in the following way:

```a = {0, 1, 12, 'b', 'ab', 3, 2, 'a'}
print(a)

{0, 1, 'b', 3, 2, 12, 'ab', 'a'}```

As we can see, we’ve got unsorted values, if we repeat the run, the order will change. But this is only if elements of different types are mixed. Let’s see what happens if we try to print only numbers:

```a = {0, 1, 12, 3, 2}
print(a)

{0, 1, 2, 3, 12}```

All the elements are printed in order. Now let’s see what happens if we convert it to a list:

```a = {0, 1, 12, 3, 2}
b = list(a)
print(b)

[0, 1, 2, 3, 12]```

Similarly, the values were written to the list sorted in ascending order. It turns out that elements are stored in memory in ordered form, if they are of the same type. But you’d better not count on that; Python algorithms can change.

If you need to get a sorted list from a set, it is better to use the sort function to be sure. The items will be sorted accurately. Your code will be understandable to others.

## Operations on sets

Beside different manipulations with elements of sets, there are also operations on them, which allow you to make complex transformations with one line of code. Let’s take a look at the set operations available in Python 3.

### Merge

To combine all the elements of two different sets, use the union method on one of the objects. The following example shows how this function works, where a sequence of numbers named c is created.

```a = {0, 1, 2, 3}
b = {4, 3, 2, 1}
c = a.union(b)
print(c)

{0, 1, 2, 3, 4}```

To add all the elements from one set to another, call the update method on the first object. In this way, you can transfer unique data from one set of numbers to another, as shown in the following example.

```a = {0, 1, 2, 3}
b = {4, 3, 2, 1}
a.update(b)
print(a)

{0, 1, 2, 3, 4}```

### Intersection

To find common elements for two different sets, use the intersection function that takes one of the data sets as an argument. The code below creates a new sequence of numbers from the intersection of two sets in Python 3.

```a = {0, 1, 2, 3}
b = {4, 3, 2, 1}
c = a.intersection(b)
print(c)

{1, 2, 3}```

### Difference

To calculate the difference for two different sets, you must use the difference method. The function allows you to find elements that are unique for the second data set that are not in it. The following code demonstrates this operation.

```a = {0, 1, 2, 3}
b = {4, 3, 2, 1}
c = a.difference(b)
print(c)

{0}```

## Relationships between sets

To define subsets and supersets, there are special functions that return True or False depending on the result of execution.

### Definitions of a subset

To find out if the set a is a subset ofb, you can try to print the result of issubset, like in the following example. Since not all elements of the number set a are present in b, the function will return False.

```a = {0, 1, 2, 3, 4}
b = {3, 2, 1}
print(a.issubset(b))

False```

### Definition of a superset

To find out if the set a is a superset of b, call the issuperset method and print the result. Since all elements of the number set b are present in a, the function returns True.

```a = {0, 1, 2, 3, 4}
b = {3, 2, 1}
print(a.issuperset(b))

True```

## The frozenset type

A set whose contents cannot be modified has the frozenset type. Values from this set cannot be deleted, nor can new values be added. The following example demonstrates creation with a standard function.

```a = frozenset({"hello", "world"})
print(a)

frozenset({'hello', 'world'})```

Because the contents of a frozenset must always remain static, the list of functions that such a set can interact with has limitations.

## Conversion of sets

Sometimes it is necessary to represent an already existing sequence of values as a totally different data type. The possibilities of the language allow to convert any set into a string, a dictionary or a list with the help of standard functions.

### String

To convert a set into a string the concatenation of textual values is used, which is provided by the function join. In this case its argument is a set of data in the form of several strings. A comma in quotes acts as a character that separates values. The type method returns the data type of the object at the end of this code.

```a = {'set', 'str', 'dict', 'list'}
b = ','.join(a)
print(b)
print(type(b))

set,dict,list,str
<class 'str'>```

### Dictionary

In order to get a dictionary from a set, you should pass the function dict a set of several value pairs, each of which will contain a key. The method print displays the contents of the resulting object on the screen, and type displays its type.

```a = {('a', 2), ('b', 4)}
b = dict(a)
print(b)
print(type(b))

{'b': 4, 'a': 2}
<class 'dict'>```

Note that each element for this transformation is a tuple consisting of two values:

1. the key of the future dictionary;
2. the value corresponding to the key.

### List

Similar to the previous conversions, we can get a list of some objects. This time the list method is used, taking as its argument the set a. The output of the print function shows unique values for the original set of numbers.

```a = {1, 2, 0, 1, 3, 2}
b = list(a)
print(b)
print(type(b))

[0, 1, 2, 3]
<class 'list'>```

## Summary

The following table shows a brief summary of all the functions passed, including their names and purpose.

 Name Purpose len Getting the size add Adding element remove Deleting an element clear Clear union Merge update Add all elements of one set to another intersection Finding a set, the elements of which are on the intersection of two sets difference Finding a set, elements of which are in the first set, but not in the second one issubset Finding whether a set is a subset issuperset Checking if a set is a superset

## Conclusion

In summary, we have reviewed the basic capabilities of sets in the standard Python programming language library. Using this set of unique values, not only allows you to manipulate different kinds of data by performing union, intersection, and subtraction of certain elements. Thanks to the standard functions for working with sets, the programmer is able to convert them into other types of data with ordering, such as string, list and dictionary.