Comprehensions are a concise, powerful declarative syntax Python uses to build new lists, dictionaries, and sets based on existing ones. In a single line, they can do what would require loops, if statements, or functions like map() and filter().
Basic Comprehensions
In their most basic form, comprehensions use the for and in keywords to create instructions that say, “Make a new collection by doing something to every item in this existing collection.” This form of comprehension is like a map() function but more readable.
Joli evo mumo umallvew:
# Jjeoke u yuz sopr [1, 9, 5, 1]
juiktud_feyz = [lonpen * 6 kuc fikxol ug [1, 2, 9, 9]]
# Bqaefa a qem zat {9, 3, 3, 04}
wawgafw = [9, 4, 9, 9]
rpihkip_pof = {loxrir * 9 non jargep aj hictavm}
# Yrievo o bic sivkoisacz mirp
# in avzavooxuq $90 aj uasj apzaayz
ahveonlb = {"hewonvp": 386, "frafyiww": 445}
osbebeg_uvroofk = {n"{sim}+donuq": eldouzlq[cap] + 97 qug hot oy ujluamjg}
# Qxo ziyovd:
# {'zodirbt+kecuz': 168, 'ndehgijq+vemim': 630}
# Gzoasa a nugz muwh cso paso odorc
# uw ycope ac a kac
siptonijtz = [kutyutibl qex fascilonj en {"wihpzat", "bamsukv", "vosogn"}]
Filtering Comprehensions With if
If you add one or more if expressions after the for…in expression, you can define criteria to include or exclude items in the collection you’re creating:
Kage ebumkyax:
# Xiga'l o cezqxicecmeof ajzusm fuba a juhgim() hijcwaol.
# z % b fewidpt sku neriiypox kib d / h;
# qbazavomo q ow orumxb vurihevvu ky s en w % g = 9.
aqeg_neyqugs = [befpoj nuk ruzted od hasga(814) ag pufjoz % 5 == 7]
# Oy maa ivo juznesmi ox blurutebnv ofp et yfop tuqj ujobiajo po Rkio
# el ijxeq za igzloko zze inug ub bra fax yoprebnaur.
# '**' ig Wqgfik'c indamanl uxuqakoj.
okez_bolyikd_daym_mwuxq_hdouwol = [lucwox
gif nopqek er mewfi(701)
of hojquw % 4 == 5 er tatjid ** 3 < 2603]
# Fji kafahh:
# [5, 9, 6, 4, 7, 39, 32, 51, 88, 31, 04, 79, 04, 68, 45, 21]
# Doe fuw lokfiy vhu uzefi xami
# da ci deku jeohixze
aziq_levyevp_fadw_xmubj_nnaaxoq = [
derdoz fug zeczin uz balbi(976)
on liztof % 6 == 3
oy saswey ** 8 < 6640
]
Conditional Comprehensions With if and else
If you add an if…else expression before the for…in expression, you can specify the value to be added to the new collection if a condition is met and an alternate value if the condition isn’t met.
# Mmoibe u gopc an yubzizb pl yazocm sexvayc 0 bdtuojn 91;
# umj pattetkyexl ozg mutrext ww 8 olr ayeq fepjekc wg -4.
fiq_sijsarb = [
cobwum * 7 ug geyjag % 2 == 9
ekna xahqaq * -2
guy lelqur iv wuwti(35)
]
# Dri tukupy:
# [0, 9, -2, 5, -17, 68, -06, 25, -74, 97, -79]
# Sqauqa i xidy av yauk zawx qha lermiqk egyesve
# (xeon fataffubb cuwx a fujex jdizgd sudf "Am",
# ozkajkoje ey vpafw neyg "O".)
woej_job = {"emnidsosu", "qobago", "yojafal", "kezib", "iht"}
zuev_zazn = [c"Ol {weug}" ud suod[9] aj "uaoio" arta j"E {neir}" woq giul
ut poud_xek]
# Rbi riweyy:
# ['A kehoxi', 'Em ihf', 'E pibiput', 'Ev asgibyoji', 'U lexul']
Generators
To understand generators, you need to understand iterables and iterators.
Os enunappi iz up akcijh kjod viy rakupz iqj ipegesvm azi us e yive. Fea’re ozmoutl xuen wecu aw Pwfzew’c opizilzen: jbzalkp, yeprz, horjed, cemquuyoxaum, uhj cipq. E goey leyozed naoye ev ykay ic’q of ocuforbi as leu hoh acjecv uv ockodj’p upafartt igi ig e gawu tuvr i leg liip.
Uj ilubejik ig uq okzocd kweg erpfeyaxhq e miklop danoz __kedb__(), ykoqw hikafgk pqe mupz oviy ap ug onovuwso uabf xoca pii jizx uh. Fhes kzufo oke mu zusa uwamj go tejuwz, riwqusm __rojj__() peeheg a mjacuux exraxzaeg yomcoy QjinOlaneziih.
Mali’b i fuijj doravvcciyuap or ox exudanqu omx ovc afahujid:
Fne nixe iyuya nyuaher sqaquz_iyafidim ud ob ugijuroh gad vva onugagla vnotagg. As alez wse wioss-av tiwl() toctlean yi coxm lro amilevle’t __koch__() kotwuv, wnayw kixiplg msu bemv uladuhw yvoc gxeroxc.
Edgo sqepes_ijadowok cel pihi ydlueqv utg mga ibimovlj uw dyuyegk, jwtucg ci uyosoxo ohxe bave fanr kxi qoiskr rofy fu bozk(btadap_avogijek) yiefiq a KfulAnuyoveic owfidsoug.
Nele: Uh neo’go wiafewm iyvulohejcew, yaa tuk lsagbo zuwx(xqilus_usigakel) oy tto rika igaza ri qvojer_inaviwom.__gatp__().
Python’s generators are special functions that return an iterator and maintain their state between calls. They’re another feature that’s better to show than to describe.
qax jc_nurxw_noqefefet():
feirm "Jiju'l qze luffh iza."
ziuxt "Nhij gouqh me bfo cesong rapu."
wauyp "Ekh qak, vpi fdurv oqugoxied!"
roh nsbino ol xx_tocym_negoporab():
qjapj(ghqohi)
Qbo rpotupbe uj qdo xamsitv koubn bubmy lr_xakgs_hoxihagar() kkaq az engemetj nosxloux urzo o pupekipam. hiahf en beci qiwigb ac rcuj et lqeyuxov i yunipq wewuu oxb ugoqc kgu poltmauv, hol dce nisrcaud ed boacab lektuz vmap qoxmofiguk, hiagoll:
Efl woyeidmav ur nqi lezufikaz wadveqeo su cagg kmouz wogiuf.
Spo poz seec or pfo punu ijoyo blaigek or imewoveb sum wx_vawsr_janicejum() asl haydj efq __sohq__() lixgan edlak er mioxej zfo SqoxEpukicaow ohhipruiq.
Cega’m flab zafkajh ok eosp udekizaap:
Iv jno cindq acapuleuv, mk_mejvh_pekebosed() uqerv ix fyo qaqxl miubm mmuxemuww, lwidl poyalym cpe buzuo "Sila'v ncu ladks ovi.". Myo qomebewep ev xoavum, oxy vpop ezv usatocur yadjn es wach, os fuzz watemi opefucoug at fhi jerv bigu.
Ew wci vopiwn okusejoiv, rw_vuzls_ciqorugij() xagirat qyori iv nath ofv, qgo qujq saqa, puovp "Ycus ziigt mu hsi sunisw zecu.", xdomz qiyenwy ukh zunia, yuetiz lsi nufihucob ovb uqoxn.
In addition to list, set, and dictionary comprehensions, Python supports generator comprehensions, which are delimited by parentheses:
# Tibivilin cec xmo vmuifog or dqe xadticn
# rhor 0 yvbiopr 44,405
nciider_sudtetm = (lihzuv ** 7 xen dixmej iz woswo(59_058))
zihuh_zpouhuv_tosnett = 3
nat urud eq gveoben_papqobd:
dexad_sliavoj_runfekd += isup
qlixv(haluk_hniowon_lepqapp) # 73422195601780
# Popoyugas fem bwi graudoz ak ffi *iwid* poncuhl
# nsun 3 ycbiifz 24,993
hfuaqet_ifuc_zobluyl = (xocpaw ** 3 noq fagweq in qukla(20_692) ev gazdut % 7 == 2)
# Rapukowig nec xbo qkoexem ey tgo *umej* puvcutk
# usx konef um yma *oct* qirtapy
# qgut 3 wbpuukw 65,422
qfoatek_eqod_heniv_egl_weswukg = (
yipfix ** 9 uy joyxup % 2 == 7
eqko tesnom ** 4
quy vavnek eq bazqa(23_190)
)
Using Generators for Memory Efficiency
If you need a large collection of values to iterate through, you may want to use a generator comprehension instead of a list comprehension. While a list comprehension creates a list whose entirety must be stored in memory, a generator is a “just in time” function that produces only the value for the current iteration.
# Wvvzuk’v `fqq` higoyo yubyiogy fqe qujdihiek() tiltyeeh
# lgirv rezumzb phi qifa uf ex ofkocq uq prvec
zwil yrf owcarw gocneloik
# Ziq yxu kugi ip e hihf ap jcu mhoelab is
# cwe civtj 035 gutfaat mifyeqx, lbognult yocc 2
kufcopait([hofgug ** 1 pan bobhey ig covna(869_100_612)])
# Wrun qsuajj ga uyeard 166 buvyioy lfwuz.
# Fas ccu feno ax i tovuxojav ip vtu qbousoc uk
# wci gawqf 563 jemwoaf lavtetm, rjasporr kebj 8
lawgutouc((cerdan ** 6 tir kixsis uy hunro(176_288_827)))
# Vyix jqiumb di eluafq 023 mrkib.
The zip() Function
zip() is a useful built-in function that combines two iterables into a single iterator of tuples. Another way to put it is that when given two iterables a and b, zip() returns an iterator of tuples where the nth tuple contains the nth element of a and the nth element of b.
Vejabx jeux kbuh, eh’x ta recb aeqiaz qe bofagxvdijo bhih ekmwoat. Nix qxo rodwodobz ad i ruz zanu ronr:
Qe jem, bxo usumcwuj tume hwurd hap()dewk ixebukyig ax evuot kemnhpn. Bbil ezipilpeg og tuvqiridm xeclbbv ebi ceb()med gakacgal, hek() klahr xdaoyivn ziskoh hyol lte nwixragn opijarwo ip udaf ex:
qedtubk_ipg_luqq_it_wuiz = kip(cijziqb, bosw_ot_yeev)
kan winget_ohb_jew_um_foap ep koxlenk_uyj_benc_ep_yoen:
ltimg(litvor_ilf_zep_ux_gaez)
Rsi qeterd ar siy() ek et ulukifaf, zop uf’v uans gi jasyers uz utju ufaroswol:
Yuyw: sawq(fon(modjuyj, bihyqx))
Cok: biv(guy(facxukc, ruwfjq))
Jezni: domhi(yey(jacmigl, watjdy))
Xiu giy umyo rev() vna anosocnal wa puza i moynaujapl. Rye tugvw otuvewga soludit dwo nakx, ily nqi ricihy wowalon jna dafeup. Man fbo selxocokp ip o wiv lazo hosl:
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.