Whencodingyouspend a lotoftimemakinglistsinmanylanguages, thiscanbetedious, created, emptylistsaiditbeforeloop, thenaddtheitemstothelist.
Onebyone.
Pythoncaresaboutyoursanityandgivesyou a tooltosimplifythisprocess.
Listcomprehension.
Inmostcases, listcomprehensionisletyouconstruct a listin a singlelineofcode.
It's nowtimeforPythontoshineandsavetimewith a singleline.
Wewillcovermanyexamplesoflistcomprehensionsze.
Butfirst, let's talkaboutthem.
Generallyinpythonlistsare a collectionofdatasurroundedbybrackets, andtheelementsareseparatedbyCommons.
A listcomprehensionisalsosurroundedbybrackets.
Butinsteadof a listofdatainside, youenteranexpressionfollowedbyfourloops.
Andifclasseshereisthemostbasicformfor a listcomprehension, thefirstexpressiongeneratestheelementsinthelist, andyoufollowthiswith a fourloopoversomecollectionofdata.
LetBebethelistofevenintegers 246 andeighttocomputetheCartesianproduct, create a listcomprehensionwhereeachtermistheTriple A B nextwrite a fourloopovertheelementsof a andthen a fourloopovertheelementsof B.