Is it possible to return 2 (or more) items for each item in a list comprehension?
What I want (example):
[f(x), g(x) for x in range(n)]
should return [f(0), g(0), f(1), g(1), ..., f(n-1), g(n-1)]
So, something to replace this block of code:
result = list()
for x in range(n):
result.add(f(x))
result.add(g(x))
Timings:
This is equivalent to
[f(1),g(1)] + [f(2),g(2)] + [f(3),g(3)] + ...
You can also think of it as:
note: The right way is to use
itertools.chain.from_iterable
or the double list comprehension. (It does not require recreating the list on every +, thus has O(N) performance rather than O(N^2) performance.) I'll still usesum(..., [])
when I want a quick one-liner or I'm in a hurry, or when the number of terms being combined is bounded (e.g. <= 10). That is why I still mention it here, with this caveat. You can also use tuples:((f(x),g(x)) for ...), ()
(or per khachik's comment, having a generator fg(x) which yields a two-tuple).Double list comprehension:
Demo:
This lambda function zips two lists into a single one:
Example: