1

This code:

def f(v):
    return (v,v+1)

a = [f(i) for i in range(3)]

gives:

[(0, 1), (1, 2), (2, 3)]

I wish to change the comprehension so that it gives:

[0, 1, 1, 2, 2, 3]

How do I do this?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Baz
  • 12,713
  • 38
  • 145
  • 268

1 Answers1

2

In a list comprehension you can use multiple for ... in ...:

>>> def f(v):
...     return (v,v+1)
...
>>> [x for i in range(3) for x in f(i)]
[0, 1, 1, 2, 2, 3]

Or, you can use itertools.chain.from_iterable:

>>> import itertools
>>> list(itertools.chain.from_iterable(f(i) for i in range(3)))
[0, 1, 1, 2, 2, 3]
falsetru
  • 357,413
  • 63
  • 732
  • 636