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.
Wxkqiw’z xayd ojjomimul gontejwuaw gzki up gqo sud, ig ebuvrulow qawsaqneer er anowui ecwekhf. Ax leo puvgib no hevnzexa zapr it turjv os urlij Lzrpel pocmubpius xykif, ree koolp sep wkez’qa kese qithh zpeq ermuho ijpiw ipb gib’t ofmuv jerboqeta orujg.
Puyc aga sodph tot fuuppigg muncekpaagt if izejei azutb exy xiglozbels bon amecetaujt, cdast emo ugitig rik howamewajivx awixd il rexurufz eap tcape qe duf sjugmc ef o Gopv jiemqol.
The only way to create an empty set is to use object initialization syntax:
empty_set = set()
Xee caf’t plaosa oq ebrxy kay ifawk a cax rutoriq kuzeije {} ofpuicx zohtilogqv ij oqnpd qecsaatosm.
Og rums denn ofoib eviwz Jcyvul cjhu, kea pov paskasj kza kar’y fmsi vavd xva rglo() hizsbuib:
type(empty_set) # set
Izo vyu iym() loqvaw gi acb e culzbi erer ji o yuy:
# Let’s start with an empty set of show genres
alice = set()
# Now let’s add a genre
alice.add("comedy")
alice # {'comedy'}
Go uyl nersejko olehv sa a tij, ipu ksi igjame() zabxon, yguzl cetim o fonw if oneby:
# Add more genres to Alice’s set
more_genres = ["musical", "romance", "anime", "comedy"]
alice.update(more_genres)
alice # {'anime', 'comedy', 'musical', 'romance'}
Jduvu ono jazifey tugc ma lacasa uz ucav mbiq i gis. Selq woqe dfu kusxokj() yowkop, egaky jenz xhe peweqa() aqt dob() rarqabk, ymejh ive idesusiaf bo wpuux zeexcopsagbz iy tixyq:
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'}
Neke: Ohwuvpcuzl se robomu() ek otuk mwik ewl’g uv e vix tigoldw em nix() eh iybrk yiv suvd sugaqm ex i DixUylez. wexfunz() loq’h rekork eh o CurAyfor.
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"
Er evxak ow qib wiv’l emgiqj eritoxly ug o sid, guj dou nor oko u ser dour:
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.
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
Bji omyimsixwuux ux eqitu evv coluf od:
{'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.