3

For example, this snippet:

out = []
for foo in foo_list:
    out.extend(get_bar_list(foo)) # get_bar_list return list with some data
return out

How to shorten this code using list comprehension?

A. Innokentiev
  • 681
  • 2
  • 11
  • 27

2 Answers2

9

You can use a generator expression and consume it with itertools.chain:

from itertools import chain

out = list(chain.from_iterable(get_bar_list(foo) for foo in foo_list))
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
5

You can use a nested list-comprehension:

out = [foo for sub_item in foo_list for foo in get_bar_list(sub_item)]

FWIW, I always have a hard time remembering exactly what order things come in for nested list comprehensions and so I usually prefer to use itertools.chain (as mentioned in the answer by Moses). However, if you really love nested list-comprehensions, the order is the same as you would encounter them in a normal loop (with the innermost loop variable available for the first expression in the list comprehension):

for sub_item in foo_list:
    for foo in get_bar_list(sub_item):
        out.append(foo)
mgilson
  • 300,191
  • 65
  • 633
  • 696