list comprehensions are one of the most-loved python language features they allow you to concisely form new list by filtering the elements of collection and transforming the elements passing the filter in one conscise expression they take the basic form[expr for val in collection if conditionthis is equivalent to the following for loopresult [for val in collectionif conditionresult append(exprthe filter condition can be omittedleaving only the expression for examplegiven list of stringswe could filter out strings with length or less and also convert them to uppercase like thisin [ ]strings [' ''as''bat''car''dove''python'in [ ][ upper(for in strings if len( out[ ]['bat''car''dove''python'set and dict comprehensions are natural extensionproducing sets and dicts in idiomatically similar way instead of lists dict comprehension looks like thisdict_comp {key-expr value-expr for value in collection if conditiona set comprehension looks like the equivalent list comprehension except with curly braces instead of square bracketsset_comp {expr for value in collection if conditionlike list comprehensionsset and dict comprehensions are just syntactic sugarbut they similarly can make code both easier to write and read consider the list of strings above suppose we wanted set containing just the lengths of the strings contained in the collectionthis could be easily computed using set comprehensionin [ ]unique_lengths {len(xfor in stringsin [ ]unique_lengths out[ ]set([ ]as simple dict comprehension examplewe could create lookup map of these strings to their locations in the listin [ ]loc_mapping {val index for indexval in enumerate(strings)in [ ]loc_mapping out[ ]{' ' 'as' 'bat' 'car' 'dove' 'python' note that this dict could be equivalently constructed byloc_mapping dict((validxfor idxval in enumerate(strings) appendixpython language essentials www it-ebooks info