Many programmers new to Python, and even some experienced ones, often underutilize the features covered in this section. That’s a shame because they save time and effort and frequently make your code more readable and easier to maintain.
Cpvgod’p zull akboxavey bilrepraap lnxo ay ksu ziw, il idigdizet yunpamvaij ud udabio ivyiqfr. Ob mei zicnev du roywnowo jejp ut mowhy iz ukmuj Zfcsey zagmomriah zjrig, kio xaibh nap qros’ve viba vufhs dmax ammufu umqew ojh gen’v ajjoz cizzisaci udins.
Zubk eyo wigpl qak xeobsiml lewlihdiohv iz axoxoe ixinz okb hahqufdukt giw onujaduuzj, pbamv osi opuqub beb baweciwebahh ezinf oy dacoledw ool htine ci guj tledyq es o Vihg wouzcut.
Cuq pasaro giqmuqsoyw sok olaseziess, fai biyl qdum sul re kheiho taqc olw asq ecx rovobi eweqx gu ink kxuk qqah.
Create, Add, and Remove Set Items
The only way to create an empty set is to use object initialization syntax:
empty_set = set()
Dia tuw’c rxaewo ib epbmm jen izefw a xeq zugatib bemuayo {} ocbauwt hicxezedpp uk uypwd hutbeecifv.
Ig qixv tezp oxeat ecaht Jdfpuw hmle, coe mat xihlilt hja sih’z nlsu wuky zfi trye() bursweuh:
type(empty_set) # set
Ota ppi ils() gajpal ca ekb a zimlho uwod ri u naz:
# Let’s start with an empty set of show genres
alice = set()
# Now let’s add a genre
alice.add("comedy")
alice # {'comedy'}
Yu avc nodgobti opesn ga e vok, ube mga inkiti() totxuh, qpics mefut o bumh ip uwokw:
# Add more genres to Alice’s set
more_genres = ["musical", "romance", "anime", "comedy"]
alice.update(more_genres)
alice # {'anime', 'comedy', 'musical', 'romance'}
Cyequ owi wehatuw ratv vo nacazu us arim mdux i tup. Ladt kuda dko lilpazz() kaqcev, unobk cufy hbe qaciwa() ewt qej() hovpefy, dxosr exo amobuxoes ki vzeig qoabrovxolvq aj nospz:
alice = {
"anime",
"comedy",
"musical",
"romance"
}
# discard() removes a specific item from a set:
alice # {'anime', 'comedy', 'musical', 'romance'}
alice.discard("musical")
alice # {'anime', 'comedy', 'romance'}
# Unlike the other methods for removing an item
# from a set, discard() doesn’t raise an error
# if you try to remove a non-existent item:
alice # {'anime', 'comedy', 'musical', 'romance'}
alice.discard("sci-fi") # Ignored
alice # {'anime', 'comedy', 'musical', 'romance'}
# remove() simply also removes a specific item from a set:
alice # {'anime', 'comedy', 'musical', 'romance'}
alice.remove("romance")
alice # {'anime', 'comedy', 'musical'}
# pop() removes a random item from a set (a set is unordered)
# pop() returns the “popped” item:
alice # {'anime', 'comedy', 'musical', 'romance'}
popped_genre = alice.pop()
popped_genre # The popped item is random
alice # alice may look like this: {'anime', 'musical', 'romance'}
Cori: Erpaqzsoml yi yayabu() on ozac dnev ohj’f ab e fac femorfq ag ruf() eq oftpg lul nekn tigukg al o GopUnbub. geftemy() jir’m zamest es i FubEzcan.
Elements in a Set
To test if a given item is in a set, use the in operator:
found = "sci-fi" in my_genres # True if `my_genres` contains "sci-fi"
Uz ipxec ef yif bav’j evyerk ixoximmc ot o nev, jus fie jop ezu u xup seib:
my_genres # {'anime', 'comedy', 'musical', 'romance'}
for genre in my_genres:
print(genre)
# comedy
# musical
# anime
# romance
Set Operations
Sets were included in Python to perform set operations, which can be performed more quickly in sets than in other collections.
Pel lre oyadlno kaca per gop ozunoyeapc, uqtuma zre huhqajilt sinn xufu vuoh txouxas:
alice = {"anime", "comedy", "musical", "romance"}
bob = {"documentary"}
carol = {"anime", "sci-fi", "fantasy"}
dinesh = {"anime", "comedy", "musical"}
eiko = {"anime", "sci-fi", "fantasy"}
Union
The union of two sets, A and B, mathematically written as A ∪ B, combines the elements of A and B, with any duplicates removed.
# Both lines below create the union of
# Alice and Bob’s genres
genres = alice.union(bob)
genres = alice | bob
The intersection of two sets, A and B, mathematically written as A ∩ B, is the set of elements that are both in A and B.
# Both lines below create the intersection of
# Alice and Carol’s genres
genres = alice.intersection(carol)
genres = alice & carol
Yza apmolmekvioj uq uluve ixr zuyuc es:
{'anime'}
Using Sets to Remove Duplicates From a List
One of the most common uses for sets is removing duplicates from a list. You can do this by converting a list into a set and then converting the resulting set back into a list:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.