You are on page 1of 16

6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

TreyHunner
programming,teaching,opensource
RSS

Search

Navigate

Blog
Archives
Talks
Projects
About
Hiremefortraining

PythonListComprehensions:ExplainedVisually
Dec1st,201510:30am|Comments

Sometimesaprogrammingdesignpatternbecomescommonenoughtowarrantitsownspecialsyntax.
Pythonslistcomprehensionsareaprimeexampleofsuchasyntacticsugar.

ListcomprehensionsinPythonaregreat,butmasteringthemcanbetrickybecausetheydontsolveanew
problem:theyjustprovideanewsyntaxtosolveanexistingproblem.

Letslearnwhatlistcomprehensionsareandhowtoidentifywhentousethem.

Update:Ihelda1hourvideochataboutlistcomprehensionswhichextendsthematerialinthisarticle.If
youwantmoreafterreadingthispost,checkouttherecording.

Whatarelistcomprehensions?
Listcomprehensionsareatoolfortransformingonelist(anyiterableactually)intoanotherlist.Duringthis
transformation,elementscanbeconditionallyincludedinthenewlistandeachelementcanbetransformed
asneeded.

Ifyourefamiliarwithfunctionalprogramming,youcanthinkoflistcomprehensionsassyntacticsugarfora
filterfollowedbyamap:

1>>>doubled_odds=map(lambdan:n*2,filter(lambdan:n%2==1,numbers))
2>>>doubled_odds=[n*2forninnumbersifn%2==1]

Ifyourenotfamiliarwithfunctionalprogramming,dontworry:Illexplainusingforloops.

Fromloopstocomprehensions
Everylistcomprehensioncanberewrittenasaforloopbutnoteveryforloopcanberewrittenasalist
comprehension.

http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 1/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

Thekeytounderstandingwhentouselistcomprehensionsistopracticeidentifyingproblemsthatsmelllike
listcomprehensions.

Ifyoucanrewriteyourcodetolookjustlikethisforloop,youcanalsorewriteitasalistcomprehension:

1new_things=[]
2forITEMinold_things:
3ifcondition_based_on(ITEM):
4new_things.append("somethingwith"+ITEM)

Youcanrewritetheaboveforloopasalistcomprehensionlikethis:

1new_things=["somethingwith"+ITEMforITEMinold_thingsifcondition_based_on(ITEM)]

ListComprehensions:TheAnimatedMovie
Thatsgreat,buthowdidwedothat?

Wecopypastedourwayfromaforlooptoalistcomprehension.

Herestheorderwecopypastein:

1.Copythevariableassignmentforournewemptylist(line3)
2.Copytheexpressionthatwevebeenappendingintothisnewlist(line6)
3.Copytheforloopline,excludingthefinal:(line4)
4.Copytheifstatementline,alsowithoutthe:(line5)

Wevenowcopiedourwayfromthis:

1numbers=[1,2,3,4,5]
2
3doubled_odds=[]
4forninnumbers:
5ifn%2==1:
6doubled_odds.append(n*2)

Tothis:

1numbers=[1,2,3,4,5]
2
3doubled_odds=[n*2forninnumbersifn%2==1]

ListComprehensions:NowinColor
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 2/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

Letsusecolorstohighlightwhatsgoingon.
doubled_odds=[]
forninnumbers:
ifn%2==1:
doubled_odds.append(n*2)

doubled_odds=[n*2forninnumbersifn%2==1]

Wecopypastefromaforloopintoalistcomprehensionby:

1.Copyingthevariableassignmentforournewemptylist
2.Copyingtheexpressionthatwevebeenappendingintothisnewlist
3.Copyingtheforloopline,excludingthefinal:
4.Copyingtheifstatementline,alsowithoutthe:

UnconditionalComprehensions
Butwhataboutcomprehensionsthatdonthaveaconditionalclause(thatifSOMETHINGpartattheend)?
Theseloopandappendforloopsareevensimplerthantheloopandconditionallyappendonesweve
alreadycovered.

Aforloopthatdoesnthaveanifstatement:

doubled_numbers=[]
forninnumbers:
doubled_numbers.append(n*2)

Thatsamecodewrittenasacomprehension:

doubled_numbers=[n*2forninnumbers]

Heresthetransformationanimated:

Wecancopypasteourwayfromasimpleloopandappendforloopby:

1.Copyingthevariableassignmentforournewemptylist(line3)
2.Copyingtheexpressionthatwevebeenappendingintothisnewlist(line5)
3.Copyingtheforloopline,excludingthefinal:(line4)

NestedLoops
Whataboutlistcomprehensionswithnestedlooping?

Heresaforloopthatflattensamatrix(alistoflists):

flattened=[]
forrowinmatrix:
forninrow:
flattened.append(n)

http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 3/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

Heresalistcomprehensionthatdoesthesamething:
flattened=[nforrowinmatrixforninrow]

NestedloopsinlistcomprehensionsdonotreadlikeEnglishprose.

Note:Mybrainwantstowritethislistcomprehensionas:
flattened=[nforninrowforrowinmatrix]

Butthatsnotright!Ivemistakenlyflippedtheforloopshere.Thecorrectversionistheoneabove.

Whenworkingwithnestedloopsinlistcomprehensionsrememberthattheforclausesremaininthesame
orderasinouroriginalforloops.

OtherComprehensions
Thissameprincipleappliestosetcomprehensionsanddictionarycomprehensions.

Codethatcreatesasetofallthefirstlettersinasequenceofwords:
first_letters=set()
forwinwords:
first_letters.add(w[0])

Thatsamecodewrittenasasetcomprehension:
first_letters={w[0]forwinwords}

Codethatmakesanewdictionarybyswappingthekeysandvaluesoftheoriginalone:
flipped={}
forkey,valueinoriginal.items():
flipped[value]=key

Thatsamecodewrittenasadictionarycomprehension:
flipped={value:keyforkey,valueinoriginal.items()}

ReadabilityCounts
Didyoufindtheabovelistcomprehensionshardtoread?Ioftenfindlongerlistcomprehensionsvery
difficulttoreadwhentheyrewrittenononeline.

RememberthatPythonallowslinebreaksbetweenbracketsandbraces.

Listcomprehension

Before

1doubled_odds=[n*2forninnumbersifn%2==1]

After

1doubled_odds=[
2n*2
3forninnumbers

http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 4/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

4ifn%2==1
5]

Nestedloopsinlistcomprehension

Before

1flattened=[nforrowinmatrixforninrow]

After

1flattened=[
2n
3forrowinmatrix
4forninrow
5]

Dictionarycomprehension

Before

1flipped={value:keyforkey,valueinoriginal.items()}

After

1flipped={
2value:key
3forkey,valueinoriginal.items()
4}

Notethatwearenotaddinglinebreaksarbitrarily:werebreakingbetweeneachofthelinesofcodewe
copypastedtomakethesecomprehension.Ourlinebreaksoccurwherecolorchangesoccurinthecolorized
versions.

Learnwithme
IdidaclassonlistcomprehensionswithPyLadiesRemoterecently.

Ifyoudliketowatchmewalkthroughanexplanationofanyoftheabovetopics,checkoutthevideo:

1.listcomprehensions
2.generatorexpressions
3.setcomprehensions
4.dictionarycomprehensions

Summary
Whenstrugglingtowriteacomprehension,dontpanic.Startwithaforloopfirstandcopypasteyourway
intoacomprehension.

Anyforloopthatlookslikethis:
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 5/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

new_things=[]
forITEMinold_things:
ifcondition_based_on(ITEM):
new_things.append("somethingwith"+ITEM)

Canberewrittenintoalistcomprehensionlikethis:
new_things=["somethingwith"+ITEMforITEMinold_thingsifcondition_based_on(ITEM)]

Ifyoucannudgeaforloopuntilitlooksliketheonesabove,youcanrewriteitasalistcomprehension.

ThisarticlewasbasedonmyIntrotoPythonclass.IfyoureinterestedinchattingaboutmyPythontraining
services,dropmealine.

LearnmorethroughweeklyPythonchats
Likemyteachingstyle?Wanttolearnmore?SignupforattendmyWeeklyPythonChateventssoIcan
answeryourquestionsaboutPython,programming,andlifeingeneral.

EmailAddress

FirstName

LastName

Subscribe

PostedbyTreyHunnerDec1st,201510:30ampython

Tweet 13

CountingthingsinPython:ahistoryMyfavoriteaudiobooksof2015

Comments

49Comments Trey'sBlog
1 Login

SortbyBest
Recommend 18 Share

Jointhediscussion

RolandSmith2yearsago
ThiswouldmakeawonderfuladditiontothePythondocumentation,especiallythenestingpart.
Theofficialdocsdon'treallycovercomprehensions.LikemostpeopleIimagineIworkeditout
bytrialanderrorinIPython,butanarticlelikethiswouldhavehelpedalot.
4 Reply Share
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 6/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner
4 Reply Share

TreyHunner Mod >RolandSmith ayearago

I'venevercontributedtothePythondocumentation,butit'ssomethingIshould
eventuallylookinto.Idon'toftenthinkofPython'sdocumentationassomethingIhave
controlovereventhoughitisopensourceandIcouldactuallycontribute.:)
Reply Share

vascowhite4monthsago
Thanksforaveryclearexplanation.Ialwayscomebackheretorefreshmymemoryonlist
comprehension.Ihavejustdiscoveredthatthisworkswithfiletoo!!

withopen('bp.txt')asfile:
readings=[line[:1].split('',5)forlineinfile]

Amazinglysimple!
2 Reply Share

TreyHunner Mod >vascowhite 4monthsago

Yup!FileobjectsinPythonareiterableandlistcomprehensionsworkanalliterables.

They'recalledlistcomprehensionsbecausethey*make*alist,notbecausetheyonlywork
forloopingoverlists.Anythingyoucanloopovercanbeusedinacomprehension.
Likewisewithsetanddictionarycomprehensionsaswellasgeneratorexpressions.

Greatobservation!
1 Reply Share

Alexis>vascowhite11daysago
Hi!Iamnotfamiliarwiththiskindofstatements
line[:1].split('',5)
whatdoesthismean?
Reply Share

CaterinaLorenteSanchoMiana5monthsago
IfindmyselfcomingbacktothismagnificentarticlewhenIgetstuckwhilewritinglist
comprehensions.So,thankyousomuchforyoutimeandeffortinwritingthispieceofgold!Itis
byfarthemostcomprehensive(pleaseforgivethepun))articleconcerninglistcomprehensions.

ItotallyagreewithRoland.ItshouldbeaddedtothePythondocumentation.

Thanksatrillion!
1 Reply Share

TreyHunner Mod >CaterinaLorenteSanchoMiana 5monthsago

ThanksCaterina!IreallyappreciatethekindwordsandI'mverygladyoufindthis
articleuseful.MaybeI'lltrymakingapullrequesttothePythondocumentationoneday.
:)
Reply Share

CaterinaLorenteSanchoMiana>TreyHunner5monthsago
Thankyouforwritingthearticleandkeepingitonline.
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 7/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner
Thankyouforwritingthearticleandkeepingitonline.
Don'tworryaboutthePythondocumentation:)

Bighug!
1 Reply Share

Tom9monthsago
Lucid,conciseandthemultipleapproachesstyleworksverywell.Subscribed.
1 Reply Share

KundanBapatayearago
AOKblog.Goodcleanexplanation.Effortscomethroughwithyouruseofcolorsand
animations.Kudos:)
1 Reply Share

TreyHunner Mod >KundanBapat ayearago

Thanks!:)
Reply Share

Martynayearago
Brilliantexplanation!I'vestruggledforawhiletofullygrasplistcomprehensionsbutitmakes
perfectsensenowthewayyou'vedescribeditandpresenteditvisually.Thanks!
1 Reply Share

EddoHintosoayearago
Imustbeanidiotorsomething,butIalwayshadsomethingagainstlistcomprehensionswhen
writingproductioncodebecauseit'snottooreadable.

Linebreaks.Howgenius.ANDitfollowsthePEP8format.

Gah.JustwhenyouthinkPythoncouldn'tbemorenaturallikeaspokenlanguage.

Thanksforthattip.Iwasreadytoflamethisarticleuntilthe'Readability'section.
1 Reply Share

ArindamRoychowdhury2yearsago
Veryniceinfo...Thenestedlistcomprehensionhelpedbefindsomesolutionstoproblemsiwas
tryingtosolveusingsimplelistcomprehension
Problem:x=[[1,2],[3,4],[5,6]],Needtoconvertto[1,2,3,4,5,6]
SolutionusingnestedLC:[mformini_listinxforminmini_list]

Mywebsite:http://thebongtraveller.blo...
1 Reply Share

TreyHunner Mod >ArindamRoychowdhury 2yearsago

Gladithelped!

Here'syetanothersolutiontoyourproblem(Iusedtostronglypreferthisovernested
comprehensions):

>>>importitertools
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 8/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner
>>>importitertools
>>>x=[[1,2],[3,4],[5,6]]
>>>y=list(itertools.chain.from_iterable(x))
>>>y
[1,2,3,4,5,6]
1 Reply Share

mamigot2yearsago
Verynice!

Thoughinsteadofthefollowingin"Nestedloopsinlistcomprehension,Before":
flattened=[nforninrowforrowinmatrix]

Isitsupposedtobethis,asyoupreviouslysay?
flattened=[nforrowinmatrixforninrow]
1 Reply Share

TreyHunner Mod >mamigot 2yearsago

You'reright.That'sthesecondplaceI'vehadtofixthat.Nicecatch!
1 Reply Share

StevenKlassen2yearsago
Thanksfortheexplanation!I'dbeenusinglistcomprehensionssparinglybutIcanseewhere
theywouldmakesomeofmysmallerloopsmoresuccinct.
1 Reply Share

TreyHunner Mod >StevenKlassen 2yearsago

IusethemmuchmorethanIusedto.

Ihighlyrecommendwritingaloopandthenwritingacomprehensionandthenbreaking
ituptoamultilinecomprehensionandseeingwhichofthemfeelsmostclear.OnceI
startedtryingthemoutmoreIfoundtheyweremoreoftenusefulthanIhadpreviously
thought.
1 Reply Share

testsite>TreyHunneramonthago
Ithinkthatratherthanwritingthesinglelinecomprehensionfirst,Iwouldstart
directlywiththemultilinecomprehension.Then,ifIwerenotsohappywiththe
wayitlooked/read,Iwoulddothesingleline,andthendecidewhichtokeep.
Reply Share

Mike2yearsago
Your"nestedloopsincomprehension"examplethrowsaNameError.Tofix,swaptheorderof
the"for"s:[nforrowinmatrixforninrow]
1 Reply Share

TreyHunner Mod >Mike 2yearsago

You'rerightIhadaccidentallyflippedthemwhenexplainingmultiline
comprehensions.Nestedloopsincomprehensionsaretricky!Thanksforpointingthat
out.Ijustfixedit.
2 Reply
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 9/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

2 Reply Share

nomel>TreyHunner2yearsago
Andnestedcomprehensionsshouldbecompletelyavoidedinanycodeyouwant
otherstounderstand,includingyourself,asyourmistakepointsout.

Forsimpleoperations,absolutely,listcomprehensionscanbemuchclearerthana
forloop.Ifyourlistcomprehensionsbecomenestedorfilledwithlambdas,you're
justwastingeveryonestimeinunderstandingthatevillittleoneliner.

Whenyouwritecode,youshouldbewritingitforthenextpersonreadingit,not
toreduceyourlinecount.There'snothingelegantaboutaconfusingoneliner.
2 Reply Share

Mike>nomel2yearsago
Idisagree.Nestedcomprehensions,usedappropriatelyandsensibly,can
makecodeFAReasiertoreadthantheequivalentforloopswithan
accumulator.It'sthedifferencebetween

"Flattenthematrix"

and

"Okayhere'sanemptylist.Whoknowswhatwe'regonnadowithit?Now,
we'regoingtoloopovertherowsofthismatrix.Iwonderwhat'scoming?
Nowwe'regoingtoloopovertheitemsintherow.Stillwithme?
Rememberthatlist?Appendthecurrentitemtoit."

Maybesomeonenewtothelanguagemightstumbleoverthem,butthey're
wellworththeefforttodevelopanintuitionfor.Forme,thelatterrequires
moreconcentrationthantheformerwhenreadingunfamiliarcode.I'm
gratefulwhenprogrammersusecomprehensionswell.

OfcourseIagreewithyourpathalogicalexampleof"filledwithlambdas"
orfarexceedingasensiblelinelength.
Reply Share

Freddie12daysago
GreatpostTrey!HoweverI'mstrugglingtryingtoconvertthefollowingcodetoalist
comprehension:

count=0
foritemsinarray:
forelementinitems:
ifelement==string:
count+=1
returncount

Itriedthisbutfailed:''.join(countforitemsinarrayforelementsinitemsifelement==string
count+=1)
Reply Share

http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 10/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

TreyHunner Mod >Freddie 12daysago

Marioiscorrectthatyoucannothavesideeffectsinyourlistcomprehensions.
Specifically,youcanonlycopypasteyourwayintoalistcomprehensionifyouhavea
singlelistappendastheonlyexpressioninyourforloop.
Reply Share

MarioWenzel>Freddie12daysago
Youcan'thavesideeffects(assignments/bindings).Trythisone:

count=sum(1foritemsinarrayforelementinitemsifelement==string)

mappingallitemsto1andtakingthesum.

Edit:butitwouldbebettertousechainfromitertoolsifyou'redoingitintwo
dimensions.

fromitertoolsimportchain
count=sum(1forelementinchain(*array)ifelement==string)
Reply Share

rickoshay22daysago
Iwouldnotcategorizethem"sugar"unlessyouwanttoconcedethateveryprogramming
statementeverenteredintoanyprograminanyprogramminglanguageisnothingmorethan
syntacticsugar.Noquestionthey'remoreorlesssweeterthanotherPythonconstructs.Imean,
considern!frommath.Ismathematicalnotation"sugar"?

Ifyouwanttocomputen!inaprocedurallanguageit'sgoingtobearathersourconstructionof
n!

Anyway,that'sofftopic.WhatIreallywantedtosayisthatlistcomprehensionsareslightlysour
versionsofsetnotationkidslearninelementaryschool.SotheanswerisPythonlist
comprehensionsareASCIIArtforsimplesetdefinitions,becausetheconventionalmathsymbols
areabitimpracticalinanyprogramminglanguage.
Reply Share

AkshayPaiamonthago
Anawesomearticle.Comprehensionsareveryusefulincertainscenariolikelistcopy:http://
sourcedexter.com/pythonlis....Thisisdefinitelyagoodarticlethathelpsmanypeopletryingto
understandashorthandnotationofcreatinglists.
Thanks!
Reply Share

TreyHunner Mod >AkshayPai amonthago

ThanksAkshay.I'drecommendthelistconstructorforasimplecopy:new_list=
list(old_list).Usinglistcomprehensionsforcopyingwithoutmodificationorfilteringis
overkill.
1 Reply Share

PedroAraujo7monthsago
Greatwork!Veryeasytounderstand...Congratulations!
CouldItranslateyourcontenttospanish?
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 11/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner
CouldItranslateyourcontenttospanish?
Reply Share

TreyHunner Mod >PedroAraujo 7monthsago

HeyPedro!Thanksforthekindwords!Pleasesendmeanemailabouttranslating.
Reply Share

whateverayearago
Asapythonnoob,canIputthepatternbelowintoalistcomprehension(andifsohow)?
Icanseehowitworksasmapwithlambda,canitworkaslistcomprehension?

Canalistcomprehensionworkasalambdathatdoesconditionaloperationsoneachelement?


Reply Share

TreyHunner Mod >whatever ayearago

You'llneedtoconvertthelistcomprehensiontothesingleappendoranappendwithif
weusedthroughoutthearticle.

ThereprimarywayIcanthinkoftodothatistowrapupthelogicthathandlesthe
"whatamIappending"intoafunction,likethis:

new_things=[]
forITEMinold_things:
new_things.append(process_item_thing(ITEM))

Thenyou'dhaveafunctionlikethis:

defprocess_item_thing(item):
ifcondition_based_on(item):
return"somethingwith"+item
else:
returnitem

Reply Share

whatever>TreyHunnerayearago
Thanks,thathelps.Alambdawrapsitup,butseemseasiesttoapplyitwitha
map.

Andthisalsohelps:http://leadsift.com/loopma...
Reply Share

TreyHunner Mod >TreyHunner ayearago

Pythonhasaninlineifstatementthatallowscodethatlookslikethis:

ifsomething:
x=one_thing
else:
x=another_thing

Tobeturnedintothis:
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 12/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

x=one_thingifsomethingelseanother_thing

Themagichereisinthestuffafterthatequalssignin(nottheassignmenttox).

Wecouldusethistochangeourfunctionintoonestatementifwewanted:

defprocess_item_thing(item):
return(
"somethingwith"+item
ifcondition_based_on(item)
elseitem
)

I'mbreakingthatovermultiplelinesforreadability,butyoucouldputitonone
seemore

Reply Share

IanNorthropayearago
HiTrey.I'mcurious,whicheditorareyouusinginyourexamples?I'mthinkingaboutlearning
emacsandwaswonderingifthatiswhatyouareusinginyourdemonstrations.Thanks.
Reply Share

TreyHunner Mod >IanNorthrop ayearago

HiIan,I'musingVim.Thecolorschemeissolarizedlightwhichisavailableinmany
editors,includingEmacsIbelieve.
Reply Share

AlexWilmerayearago
Veryhelpful!
Reply Share

LvdiWangayearago
Nice!BestexplanationIhaveseensofar.
Reply Share

unknownayearago
Questionaboutconvertingnestedloopintoalistcomprehension.
HowcanIaddaconditiontothislist?

soletssaymyloopsarelikebelow.....
forainmatrix:
foriina:
ifi%2==0:
result.append(i)

Cananyoneexplainthisplease?
Thanks.
Reply Share

TreyHunner Mod >unknown ayearago

Youcanaddaconditionalclausejustlikeinacomprehensionwithoutnestedloops.
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 13/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

flattened=[iforainmatrixforiinaifi%2==0]

Explanation:

Reply Share

unknown>TreyHunnerayearago
Perfect.Thanksveryveryverymuch.
Reply Share

AlistairBroomhead2yearsago
TheconfusingsyntaxofthenestedcomprehensionisonereasonwhyIdon'tusethemmuch,
whatIdousealot,andareperhapsworthmentioninghere,aregeneratorexpressions.

Theselookalotlikealistcomprehension,butusingparenthesesinsteadofsquarebrackets.The
importantdifferenceisthatthisreturnsaniterablewhichislazilyevaluated,andsocanbeused
inalotofcircumstanceswherealistcomprehensionwouldbewasteful,orcanbeusedtobuild
upapipelineofoperations.

I'veattachedarathercontrivedexample,whereyoucanuseageneratorexpressiontoignorethe
lengthofanonlysource,onlyreadinguptothepointwhereyouhavecompletedyourtask.


Reply Share

TreyHunner Mod >AlistairBroomhead ayearago

Icompletelyagree.Iusegeneratorexpressionswheneverpossible.Iconsidered
explainingtheminthispostbutIthinkthey'llwarrantapostoftheirowntoexplainhow
theyworkandwhythey'resogreat.

Thanksfortheexample!
Reply Share

AlistairBroomhead>TreyHunnerayearago
Ithinkexploringthemfullyisprobablyfodderforareasonablyadvancedpost,
butit'sworthmentioningtheminpassingduetotheirvisualsimilarity,andthe
falseexpectationthattheymightbeatuplecomprehension.

Knowinghowtousethemmaybetrickytoexplain,butknowingtheyexistis
perhapsimportanttoavoidmistakes.
1 Reply Share
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 14/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner
1 Reply Share

AlistairBroomhead>AlistairBroomhead2yearsago
It'sworthknowingabouttheseevenifyoudon'tintendtousethem,assyntacticallyyou
mayexpectthistobeatuplecomprehension.
Reply Share

DanPatterson2yearsago
acomparisonofwhyIlikenestedcomprehensionsisthatyoucanprovidecomments(thelackof
appropriatefontdoesn'tdoitcompletejustice,butyougetmydrift)

#forma
a=[i**2foriinrange(10)ifi>2andi<8]

#formb
b=[i**2#dothis
foriinrange(10)#usingthese
if(i>2)and#wherethisand
(i<8)#thisisgood
]#thatisall
Reply Share

MarioWenzel2yearsago
foranestedloop,whentheinnerloopdoesnotdependontheouterloop,considerusing
itertools.productforthecrossproducttoiterateoverallpossiblecombinations.Thisisvery
usefulforlistcomprehension.
Reply Share

ALSOONTREY'SBLOG

Pong CountingThingsinPython:AHistory
3comments6yearsago 18comments2yearsago

WeeklyPythonChat
IfyoureacuriousPythonprogrammerlookingtodiscoverwhatelsethereistolearn,signupformyemail
list!

IhostaliveWeeklyPythonChatduringwhichIansweryourquestionsaboutPython,freelancing,
leadership,teaching,andotherstuff.

Youremail Subscribe

RecentPosts

MyFavoriteAudiobooksof2016
TheIteratorProtocol:HowforLoopsWorkinPython
CheckWhetherAllItemsMatchaConditioninPython
WeeklyPythonChat:LiveFromPyCon
HowtoLoopWithIndexesinPython
Webinar:RegularExpressionsinPython
TheIdiomaticWaytoMergeDictionariesinPython
http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 15/16
6/3/2017 PythonListComprehensions:ExplainedVisuallyTreyHunner

FindMeOnline

TreyHunner

Copyright2017TreyHunnerPoweredbyOctopress

http://treyhunner.com/2015/12/pythonlistcomprehensionsnowincolor/ 16/16