Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension: Returning two (or more) items for each item

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)) 
like image 731
Hashmush Avatar asked Aug 08 '12 16:08

Hashmush


People also ask

What does a list comprehension return?

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.

Can list comprehension return two lists?

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.

What is a nested list comprehension?

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.


1 Answers

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] 
like image 115
ninjagecko Avatar answered Oct 06 '22 08:10

ninjagecko