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 ]
  • 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 2

new_list = [ i * 2 for i in [1,2,3,"b",4,5] ]
print(new_list)

Result:

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

Example: Multiply each integer element of a list by 2, skip characters

new_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]

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.

  1. filter_odd filters for modification only odd numbers
  2. mult, multiplies each number that filter_odd allows with m, where m is equal to 2, then adds the result to a new list
def mult(i,m):
return i*m
def generate_numbers(start,stop):
for j in range(start,stop):
yield j
def filter_odd(i):
if i%2 > 0:
return True
else:
return False
if __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 100

pairs = {}
pairs['a'] = 10
pairs['b'] = 50
pairs['c'] = 133
pairs['d'] = 200
if __name__ == '__main__':new_dict = dict([ (k,v) for k,v in pairs.items() if v > 100 ])
print(new_dict)
  1. filter only the pair that v(alue) is greater than 100
  2. create a tuple with the filtered pair and add it to a list
  3. convert the list to a dictionary

Result:

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

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store