0

I want to write a list like [i*2, i*3 for i in range(10)] so that I can have an output of [0, 0, 2, 3, 4, 6, 6, 9, 8, 12...] (so for each element in the range(10) I want to add 2 elements to the list from two calculations).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Matthew Miles
  • 727
  • 12
  • 26

4 Answers4

4

Use itertools.chain.from_iterable, or any other Python iterable-flattening approach:

>>> list(itertools.chain.from_iterable([(i*2, i*3) for i in range(10)]))
[0, 0, 2, 3, 4, 6, 6, 9, 8, 12, 10, 15, 12, 18, 14, 21, 16, 24, 18, 27]
blacksite
  • 12,086
  • 10
  • 64
  • 109
  • Don't really need to pass as list: `list(itertools.chain.from_iterable((i*2, i*3) for i in range(10)))`. its fine to just pass a generator. – RoadRunner May 11 '20 at 14:22
2

Updated:

[ i*k for i in range(10) for k in (2, 3) ]

Original:

Just keeping it simple with list comprehension:

[ i*k for i in range(10) for k in range(2,4) ]
ilyankou
  • 1,309
  • 8
  • 13
1

How about two for statements in a list comprehension?

[i*j for i in range(10) for j in [2, 3]]
0
sum((map(lambda x: [x*2, x*3], range(10))), [])

output

[0, 0, 2, 3, 4, 6, 6, 9, 8, 12, 10, 15, 12, 18, 14, 21, 16, 24, 18, 27]

we can do it this way too, without any loops.

Santhosh Reddy
  • 123
  • 1
  • 6