Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension to produce two values in one iteration

I want to generate a list in python as follows -

[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....] 

You would have figured out, it is nothing but n, n*n

I tried writing such a list comprehension in python as follows -

lst_gen = [i, i*i for i in range(1, 10)] 

But doing this, gives a syntax error.

What would be a good way to generate the above list via list comprehension?

like image 572
user1629366 Avatar asked May 16 '13 18:05

user1629366


People also ask

Can list comprehension be nested?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.


2 Answers

Use itertools.chain.from_iterable:

>>> from itertools import chain >>> list(chain.from_iterable((i, i**2) for i in xrange(1, 6))) [1, 1, 2, 4, 3, 9, 4, 16, 5, 25] 

Or you can also use a generator function:

>>> def solve(n): ...     for i in xrange(1,n+1): ...         yield i ...         yield i**2  >>> list(solve(5)) [1, 1, 2, 4, 3, 9, 4, 16, 5, 25] 
like image 110
Ashwini Chaudhary Avatar answered Sep 25 '22 02:09

Ashwini Chaudhary


The question is old, but just for the curious reader, i propose another possibility: As stated on first post, you can easily make a couple (i, i**2) from a list of numbers. Then you want to flatten this couple. So just add the flatten operation in your comprehension.

[x for i in range(1, 10) for x in (i,i**2)] 
like image 25
Yann Avatar answered Sep 23 '22 02:09

Yann