This question already has an answer here:
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?
This question already has an answer here:
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?
You can use a nested list-comprehension:
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):You can use a generator expression and consume it with
itertools.chain
: