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))
List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
The question was: 'is it possible to return two lists from a list comprehension? '. I answer that it is possible, but in my opinion is better to iterate with a loop and collect the results in two separate lists.
It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.
Double list comprehension:
[f(x) for x in range(5) for f in (f1,f2)]
Demo:
>>> f1 = lambda x: x >>> f2 = lambda x: 10*x >>> [f(x) for x in range(5) for f in (f1,f2)] [0, 0, 1, 10, 2, 20, 3, 30, 4, 40]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With