Dobrodošli
U ovom ćete članku naučiti osnove skupova u Pythonu. Ovo je vrlo moćan ugrađeni tip podataka koji možete koristiti u svojim Python projektima.
Istražit ćemo:
- Koji su to skupovi i zašto su relevantni za vaše projekte.
- Kako stvoriti set.
- Kako provjeriti nalazi li se element u skupu.
- Razlika između skupova i frozenseta.
- Kako raditi sa skupovima (u ovom ćemo dijelu zaroniti u osnove teorije skupova).
- Kako dodati i ukloniti elemente iz skupova i kako ih obrisati.
Započnimo! ⭐️
? Postavlja u kontekstu
Dopustite mi da vam kažem zašto biste željeli koristiti skupove u svojim projektima. U matematici je skup skup različitih predmeta. U Pythonu je ono što ih čini tako posebnima činjenica da nemaju duplicirane elemente pa se mogu koristiti za učinkovito uklanjanje dupliciranih elemenata s popisa i korpica.
Prema Python dokumentaciji:
Python također uključuje tip podataka za skupove . Skup je nesređena zbirka bez dupliciranih elemenata. Osnovne namjene uključuju testiranje članstva i uklanjanje dvostrukih unosa.❗️Važno: Elementi skupa moraju biti nepromjenjivi (ne mogu se mijenjati). Nepromjenjive vrste podataka uključuju nizove, korijene i brojeve kao što su cjelobrojni i plutajući podaci.
? Sintaksa
Da bismo stvorili skup, započinjemo s pisanjem par kovrčavih zagrada, {}
a unutar tih kovrčavih zagrada uključujemo elemente skupa odvojene zarezom i razmakom.

? Savjet: primijetite da se ova sintaksa razlikuje od Pythonovih rječnika jer ne stvaramo parove ključ / vrijednost, već pojedine elemente uključujemo u kovrčave zagrade {}
.
Postavi ()
Alternativno, možemo koristiti funkciju set () za stvaranje skupa (vidi dolje).
Da bismo to učinili, dodali bismo iterabil (na primjer, popis, niz ili tuple) i taj bi se iterabil pretvorio u skup uklanjajući sve duplicirane elemente.

Ovo je primjer u IDLE-u:
# Set >>> {1, 2, 3, 4} {1, 2, 3, 4} # From a list >>> set([1, 2, 3, 4]) {1, 2, 3, 4} # From a tuple >>> set((1, 2, 3, 4)) {1, 2, 3, 4}
? Savjet: Da biste stvorili prazan skup, morate koristiti funkciju set () jer će se pomoću praznog skupa kovrčavih zagrada, poput ovog {}
, automatski stvoriti prazan rječnik , a ne prazan skup.
# Creates a dictionary, not a set. >>> type({}) # This is a set >>> type(set())
? Dvostruki elementi se uklanjaju
Ako iterabil koji prosljeđujete kao argument set()
ima dvostruke elemente, oni se uklanjaju radi stvaranja skupa.
Na primjer, primijetite kako se uklanjaju duplicirani elementi kada prođemo ovaj popis:
>>> a = [1, 2, 2, 2, 2, 3, 4, 1, 4] >>> set(a) {1, 2, 3, 4}
i primijetite kako se dvostruki znakovi uklanjaju kada proslijedimo ovaj niz:
>>> a = "hhheeelllooo" >>> set(a) {'e', 'l', 'o', 'h'}
? Duljina
Da biste pronašli duljinu skupa, možete koristiti ugrađenu funkciju len ():
>>> a = {1, 2, 3, 4} >>> b = set(a) >>> len(b) 4
U matematici se broj elemenata skupa naziva " kardinalnost " skupa.
Sting Testiranje članstva
Možete testirati je li neki element u skupu s in
operatorom:

Ovo u primjeru:
>>> a = "hhheeelllooo" >>> b = set(a) >>> b {'e', 'l', 'o', 'h'} # Test if the characters 'e' and 'a' are in set b >>> 'e' in b True >>> 'a' in b False
? Setovi protiv Frozensetsa
Setovi su promjenjivi, što znači da ih je moguće modificirati nakon što su definirani.
Prema Python dokumentaciji:
set
Tip je
promjenjiv - sadržaj se može mijenjati pomoću metode kao što su
add()
i
remove()
. Budući da je promjenjiv, nema hash vrijednost i ne može se koristiti ni kao ključ rječnika ni kao element drugog skupa.
Budući da ne mogu sadržavati vrijednosti promjenjivih tipova podataka, ako pokušamo stvoriti skup koji sadrži skupove kao elemente (ugniježđeni skupovi), vidjet ćemo ovu pogrešku:
TypeError: unhashable type: 'set'
Ovo je primjer u IDLE-u. Primijetite kako su elementi koje pokušavamo uključiti skupovi:
>>> a = {{1, 2, 3}, {1, 2, 4}} Traceback (most recent call last): File "", line 1, in a = {{1, 2, 3}, {1, 2, 4}} TypeError: unhashable type: 'set'
Frozensets
Da bismo riješili taj problem, imamo drugu vrstu skupa nazvanu frozensets.
Oni su nepromjenjivi , takone mogu se mijenjati i možemo ih koristiti za stvaranje ugniježđenih skupova.
Prema Python dokumentaciji:
frozenset
Tip je nepromjenjiva i hashable - njegov sadržaj ne mogu se mijenjati nakon što je stvorio; stoga se može koristiti kao ključ rječnika ili kao element drugog skupa.
Da bismo stvorili zamrznuti set, koristimo:

? Savjet: Prazni smrznuti skup možete stvoriti pomoću frozenset()
.
Ovo je primjer skupa koji sadrži dva frozenseta:
>>> a = {frozenset([1, 2, 3]), frozenset([1, 2, 4])} >>> a {frozenset({1, 2, 3}), frozenset({1, 2, 4})}
Primijetite da ne dobivamo nikakve pogreške i skup je uspješno stvoren.
? Uvod u teoriju skupova
Prije ulaska u skupove operacija, moramo istražiti malo teorije skupova i Vennovih dijagrama. Zaronit ćemo u svaku postavljenu operaciju s pripadajućim ekvivalentom u Python kodu. Započnimo.
Subsets and Supersets
You can think of a subset as a "smaller portion" of a set. That is how I like to think about it. If you take some of the elements of a set and make a new set with those elements, the new set is a subset of the original set.
It's as if you had a bag full of rubber balls of different colors. If you make a set with all the rubber balls in the bag, and then take some of those rubber balls and make a new set with them, the new set is a subset of the original set.
Let me illustrate this graphically. If we have a set A with the elements 1, 2, 3, 4:
>>> a = {1, 2, 3, 4}
We can "take" or "select" some elements of a and make a new set called B. Let's say that we chose to include the elements 1 and 2 in set B:
>>> a = {1, 2, 3, 4} >>> b = {1, 2}
Every element of B is in A. Therefore, B is a subset of A.
This can be represented graphically like this, where the new set B is illustrated in yellow:

? Note: In set theory, it is a convention to use uppercase letters to denote sets. This is why I will use them to refer to the sets (A and B), but I will use lowercase letter in Python (a and b).
.issubset()
We can check if B is a subset of A with the method .issubset():
>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b.issubset(a) True
As you can see, B is a subset of A because the value returned is True
.
But the opposite is not true since not all the element of A are in B:
>>> a.issubset(b) False
Let's see something very interesting:
>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a.issubset(b) True >>> b.issubset(a) True
If two sets are equal, one is a subset of the other and vice versa because all the elements of A are in B and all elements of B are in A. This can be illustrated like this:

Using <=
We can achieve the same functionality of the .issubset()
method with the <=
comparison operator:
>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a <= b True
This operator returns True
if the left operand is a subset of the right operand, even when the two sets are equal (when they have the same elements).
Proper Subset
But what happens if we want to check if a set is a proper subset of another? A proper subset is a subset that is not equal to the set (does not have all the same elements).
This would be a graphical example of a proper subset. B does not have all the elements of A:

To check this, we can use the <
comparison operator:
# B is not a proper subset of A because B is equal to A >>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> b >> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b < a True
Superset
This can be illustrated like this (see below), where A is a superset of B:

.issuperset()
We can test if a set is a superset of another with the .issuperset() method:
>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a.issuperset(b) True
We can also use the operators >
and >=
. They work exactly like <
and <=
, but now they determine if the left operand is a superset of the right operand:
>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a > b True >>> a >= b True
Disjoint Sets
Two sets are disjoint if they have no elements in common. For example, here we have two disjoint sets:

.isdisjoint()
We can check if two sets are disjoint with the .isdisjoint() method:
# Elements in common: 3, 1 >>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a.isdisjoint(b) False # Elements in common: None >>> a = {3, 1, 4} >>> b = {8, 9, 0} >>> a.isdisjoint(b) True
? Set Operations
We can operate on sets to create new sets, following the rules of set theory. Let's explore these operations.
Union
This is the first operation that we will analyze. It creates a new set that contains all the elements of the two sets (without repetition).

This is an example:
>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> a | b {1, 2, 3, 4, 7, 8}
? Tip: We can assign this new set to a variable, like this:
>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = a | b >>> c {1, 2, 3, 4, 7, 8}
In a diagram, these sets could be represented like this (see below). This is called a Venn diagram, and it is used to illustrate the relationships between sets and the result of set operations.

We can easily extend this operation to work with more than two sets:
>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = {1, 0, 4, 6} >>> d = {8, 2, 6, 3} # Union of these four sets >>> a | b | c | d {0, 1, 2, 3, 4, 6, 7, 8}
? Tip: If the union contains repeated elements, only one is included in the final set to eliminate repetition.
Intersection
The intersection between two sets creates another set that contains all the elements that are inboth A and B.

This is an example:
>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a & b {1, 3}
The Venn diagram for the intersection operation would be like this (see below), because only the elements that are in both A and B are included in the resulting set:

We can easily extend this operation to work with more than two sets:
>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} # Only 5 is in a, b, c, and d. >>> a & b & c & d {5}
Difference
The difference between set A and set B is another set that contains all the elements of set A that are not in set B.

This is an example:
>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a - b {6}
The Venn diagram for this difference would be like this (see below), because only the elements of A that are not in B are included in the resulting set:

? Tip: Notice how we remove the elements of A that are also in B (in the intersection).
We can easily extend this to work with more than two sets:
>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} # Only 7 is in A but not in B and not in C >>> a - b - c {7}
Symmetric Difference
The symmetric difference between two sets A and B is another set that contains all the elements that are in either A or B, but not both. We basically remove the elements from the intersection.

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a ^ b {2, 6, 8}
The Venn diagram for the symmetric difference would be like this (see below), because only the elements that are in either A or B, but not both, are included in the resulting set:

We can easily extend this to work with more than two sets:
>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} >>> a ^ b ^ c ^ d {0, 1, 3, 7}
Update Sets Automatically
If you want to update set A immediately after performing these operations, you can simply add an equal sign after the operator. For example:
>>> a = {1, 2, 3, 4} >>> b = {1, 2} # Notice the &= >>> a &= b >>> a {1, 2}
We are assigning the set that results from a & b
to set a
in just one line. You can do the same with the other operators: ^=
, |=
, and -=
.
? Tip: This is very similar to the syntax that we use with variables (for example: a += 5
) but now we are working with sets.
? Set Methods
Sets include helpful built-in methods to help us perform common and essential functionality such as adding elements, deleting elements, and clearing the set.
Add Elements
To add elements to a set, we use the .add() method, passing the element as the only argument.
>>> a = {1, 2, 3, 4} >>> a.add(7) >>> a {1, 2, 3, 4, 7}
Delete Elements
There are three ways to delete an element from a set: .remove()
,.discard()
, and .pop()
. They have key differences that we will explore.
The first two methods (.remove() and .discard()) work exactly the same when the element is in the set. The new set is returned:
>>> a = {1, 2, 3, 4} >>> a.remove(3) >>> a {1, 2, 4} >>> a = {1, 2, 3, 4} >>> a.discard(3) >>> a {1, 2, 4}
The key difference between these two methods is that if we use the .remove() method, we run the risk of trying to remove an element that doesn't exist in the set and this will raise a KeyError
:
>>> a = {1, 2, 3, 4} >>> a.remove(5) Traceback (most recent call last): File "", line 1, in a.remove(5) KeyError: 5
We will never have that problem with .discard() since it doesn't raise an exception if the element is not found. This method will simply leave the set intact, as you can see in this example:
>>> a = {1, 2, 3, 4} >>> a.discard(5) >>> a {1, 2, 3, 4}
The third method (.pop()) will remove and return an arbitrary element from the set and it will raise a KeyError
if the set is empty.
>>> a = {1, 2, 3, 4} >>> a.pop() 1 >>> a.pop() 2 >>> a.pop() 3 >>> a {4} >>> a.pop() 4 >>> a set() >>> a.pop() Traceback (most recent call last): File "", line 1, in a.pop() KeyError: 'pop from an empty set'
Clear the Set
You can use the .clear()
method if you need to delete all the elements from a set. For example:
>>> a = {1, 2, 3, 4} >>> a.clear() >>> a set() >>> len(a) 0
? In Summary
- Sets are unordered built-in data types that don't have any repeated elements, so they allow us to eliminate repeated elements from lists and tuples.
- They are mutable and they can only contain immutable elements.
- We can check if a set is a subset or superset of another set.
- Frozenset is an immutable type of set that allows us to create nested sets.
- We can operate on sets with: union (
|
), intersection (&
), difference (-
), and symmetric difference (^
). - We can add elements to a set, delete them, and clear the set completely using built-in methods.
I really hope you liked my article and found it helpful. Now you can work with sets in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️