Sets in Python
![]()
In today’s article we will explore sets in Python. You must have learnt in your Math class about sets and if you remember a set is a collection of elements but today we will dig into the details of sets in Python which is close to, but not the same as, mathematical sets. Set is one of the four built-in data types in Python along with List, Tuple, and Dictionary, all with different qualities and usage. It is used to store collections of data and are written with curly brackets.
In Python, sets store unordered values and cannot have multiple occurrences of the same element. It makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections. For example, let S be a set of even numbers less than or equal to 10.
As I said, sets can neither have any order nor have repeated values.
You can see in the above code each element can appear in the set only once. Now, Let W be a set
In the example above, the order of the set W is not preserved.
Initialize a Set
In order to create a new empty set, you use set()
Add and Delete Values from a Set
We can use update() to add new elements to a set. It adds elements from a set (passed as an argument) to the set. In the example below, I have used update() to add new elements to the empty set S.
To delete an element from a set. We can use remove() and it only works if the element to be deleted is present in the set.
Whereas discard() works whether the element to be deleted is present in the set or not.
We can use pop() to remove a random element from the set.
In order to get a sorted list from a set, we use sorted() function.
Immutable Elements
Although a set is mutable i.e. we can add or remove elements from it, the elements of a set are immutable (cannot be changed). Immutable objects include numbers, strings and tuples. In the example below you can see that the elements of a set can be tuples.
but they cannot be lists.
Operations on sets
Python defines many operations on sets. Most operations come in two forms, as a method and as an overload of mathematical operators.
Element of or belongs to: To check if an element is in a set or not we use “in” and “not in” operators.
Subset (A⊆B ): A is a subset of B if set A is included in set B. In other words, all the elements in set A are also elements of set B. You can see in the diagram below. To investigate in Python, whether a set A is a subset of another set B or not, we use issubset() or <=.
Superset (B⊇A): B is a superset of A is another way of saying that A is a subset of B. To examine it in Python, we use issuperset() or >=.
Union (A⋃B): A⋃B has all the elements that belong either to set A or to set B. To find union in Python, we use union() or |.
Intersection (A⋂B): A⋂B has all the elements that belong to both set A and set B. To determine intersection in Python, we use intersection() or &.
Difference (B-A): B-A contains all elements that are in B and not in A. To evaluate difference in Python, we use difference() or -.
Symmetric Difference (A △ B): A △ B comprises all elements that belong to A or B but not to their intersection or contains all elements that are in one of the two sets, but not in both. We use the method symmetric_difference() or ^, to find symmetric difference in Python.
Computing the cartesian Product
The Cartesian product of two sets A and B, denoted A × B, is the set of all possible ordered pairs where the elements of A are first and the elements of B are second. In set-builder notation, A × B = <(a, b) : a ∈ A and b ∈ B>. The code snippet below computes the cartesian product of two sets A and B in Python.
Conclusion
In this article, we have learnt about sets in Python, how to create a set, how to add and remove elements from a set. We went over the operations that can be applied on sets. We also saw that sets themselves are mutable but their elements are immutable. Thank you for reading. I hope you found this article useful. If you have any questions, feel free to reach out in the comments below or through Twitter. Happy Pythoning!
Как добавить элемент в множество python









- Теория
- Практика
- Stepik.org
Множество (set)
Множество (set) — неупорядоченная коллекция, хранящая набор уникальных значений и поддерживающая для них операции добавления, удаления и определения вхождения.
Также объект множество в Python поддерживает операции, аналогичные операциям с математическими множествами: объединение, пересечение, симметричная разность и вычитание множеств
Создание множества
Множество создается перечислением через запятую всех элементов внутри фигурных скобках.
В случае, если имеются повторяющиеся элементы внутри фигурных скобок, дубли во множестве все равно исчезнут. Множество не терпит среди элементов повторения.
Пустое множество создается при помощи функции set()
Также при помощи функции set() можно создавать множества из других объектов. Если передать строку, то получим множество из символов этой строки.
Также можно передавать функции set() списки и функцию range().
Добавление элемента в множество
Первый способ добавить элемент в множество это вызвать метод add(). При попытке добавить уже существующий элемент во множество никаких ошибок не возникнет
Второй способ добавить элемент в множество это вызвать метод update() и передать ему итерируемый объект: список, строку, range() или множество. Метод update() будет поочередно добавлять каждый элемент итерируемого объекта внутрь множества.
Удаление элемента из множество
Первый способ удалить элемент из множества это вызвать метод discard(value) и передать ему значение, которое хотите удалить. В случае, если в множестве нет значения, исключений не будет.
Второй способ удалить элемент — это вызвать метод remove(value). В случае, если указанного значения в множестве нет, возбуждается исключение KeyError.
Третий способ удалить элемент — вызвать метод pop(). Т.к. множество является неупорядоченной коллекцией, данный метод удалит случайный элемент. При попытке удалить элемент из пустого множества возникнет исключение KeyError.
Операции над множеством
Нахождение длины
Проверка вхождения элемента во множество
Пересечение множеств
При помощи оператора & можно выполнить пересечение множеств. В результат попадут те элементы, которые одновременно принадлежат двум множествам. При этом сами множества не меняются. Если нужно изменить само множество используйте эту операцию с присвоением &=.
Объединение множеств
При помощи оператора | можно выполнить объединение множеств. В результат попадут те элементы, которые принадлежат хотя бы одному из множеств. При этом сами множества не меняются. Если нужно изменить само множество используйте эту операцию с присвоением |=.
Вычитание множеств
При помощи оператора — можно выполнить вычитание множеств. В результат попадут только те элементы, которые принадлежат первому множеству за исключение тех, которые входят во второе.