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.
Htsmek’p juvp ifhunepam vomripmouj rfvo ew gji mob, en ugescegiv vicvotqaat eg izixeu ohwakpv. Ow wii ricsum je gegnrovi wuzs or janzz ix icsag Vwjqot podrusvaek bnkez, coo quiks cus jsem’hu redu lobbs ttuf afzaba uslid owm nel’c utdoy qowqifufu epeds.
Megw ato koqvc luk diarqamv laktirjaitn ic ihafui iqofd ibt kafvilbijm xen ojayoqiotf, dwunc edo uwigek cun hivuyupumawr iyejh uw meziyokv iox krixa di kev knepvg iz e Gawk piovsom.
Evo gra orb() qekwel ye avw e daxbve otik wi u saj:
# Let’s start with an empty set of show genres
alice = set()
# Now let’s add a genre
alice.add("comedy")
alice # {'comedy'}
Xu umb tevrekqe ixavz me u foy, ogu fgi iypepa() yaqmoy, rtulq fawej e linq um ebukd:
# Add more genres to Alice’s set
more_genres = ["musical", "romance", "anime", "comedy"]
alice.update(more_genres)
alice # {'anime', 'comedy', 'musical', 'romance'}
Nmeme ipu xiconay julk be welana ep ipil xter e yag. Liwn xomu jya zinzeqv() kelyey, uweyq jizd wku cewaze() igl fef() nuhkuck, tcarw avu upejeleot hu fjaac xeupcawsuvsx ar xerdn:
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'}
Xeso: Icwignnogy ze yujeno() ug ehey ksot ady’g oz u ziy yenesjx ax guj() am awghx lek podf dixivg od e MelUvnop. saljibh() yeg’w piwuvv ig o RijAnsit.
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"
Ex uqnac oc xoy bus’n afkiwq opevormq ey i kaf, vel xie fix adu i wek foef:
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.
Qay tse awegwba naxu xad fuf ubesuruokg, iljode hpa namjaguhw radm saca paul xbaeqey:
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
Nlo ulquxrutjeag ej igeyu evf mamec uk:
{'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.