Python: List Comprehension tricks

List comprehension is used to create new lists from existing iterables, usually the list comprehension code is an one liner that is more readable than a long function. The generic syntax of a list comprehension is[ expression context condition ]

Syntax Explanation

  • []: The surrounding brackets mean that the result is a new list
  • context: elements of an object that is iterable.
  • expression: defines how each element of the object to modified before added to the new list
  • condition: its optional, defines which element of the context to be modified

Example: Multiply each element of a list by 2new_list = [ i * 2 for i in [1,2,3,"b",4,5] ]
print(new_list)

Result:[2, 4, 6, 'bb', 8, 10]

Notice that if we multiply a character by 2, the result will be the character twice

Example: Multiply each integer element of a list by 2, skip charactersnew_list = [ i * 2 for i in [1,2,3,"b",4,5] if isinstance(i,int) ]
print(new_list)

Result:[2, 4, 6, 8, 10]

Using the if isinstance(i,int)condition we filtered out the non integer elements of the list.

Example: Use functions within the list comprehension

The context, expression and condition parts of a list comprehension can be user functions if you need to write something that requires more complex code.

This code does the following:

  1. generate_numbers function yields numbers from 1 to 6
  2. filter_odd filters for modification only odd numbers
  3. mult, multiplies each number that filter_odd allows with m, where m is equal to 2, then adds the result to a new listdef mult(i,m):
       return i*mdef generate_numbers(start,stop):
       for j in range(start,stop):
           yield jdef filter_odd(i):
       if i%2 > 0:
           return True
       else:
           return Falseif __name__ == '__main__':new_list = [ mult(i,m=2)  for i in generate_numbers(start=1,stop=6) if filter_odd(i=i) ]
       print(new_list)

Result:[2, 6, 10]

Example: List comprehension with dictionaries

List comprehension can iterate dictionaries as well, the bellow code will create a new dictionary where values of an existing dictionary are greater than 100pairs = {}
pairs['a'] = 10
pairs['b'] = 50
pairs['c'] = 133
pairs['d'] = 200if __name__ == '__main__':new_dict = dict([ (k,v)  for k,v in pairs.items() if v > 100 ])
   print(new_dict)

This code does the following:

  1. for each k(ey) and v(alue) of pairs
  2. filter only the pair that v(alue) is greater than 100
  3. create a tuple with the filtered pair and add it to a list
  4. convert the list to a dictionary

Result:{'c': 133, 'd': 200}

I hope you found this article interesting and help you write great one-liners ;)