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
  • 601
  • 1
  • 10
  • 26

2 Answers2

8

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
  • 74,909
  • 8
  • 119
  • 129
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
  • 283,004
  • 58
  • 591
  • 667