python list comprehension to produce two values in one iteration

user1629366 picture user1629366 · May 16, 2013 · Viewed 32.4k times · Source

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?

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · May 16, 2013

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]