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).
Asked
Active
Viewed 159 times
0

jonrsharpe
- 115,751
- 26
- 228
- 437

Matthew Miles
- 727
- 12
- 26
-
6`[x for i in range(10) for x in (i * 2, i * 3)]`? Note it will also include two zeros. – jonrsharpe May 11 '20 at 14:00
-
1Why are the best answers always left as comments @jonrsharpe – Matthew Miles May 11 '20 at 14:14
4 Answers
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]]

Oguz Incedalip
- 21
- 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
-
I don't understand why my answer is irrelevant? can anyone please explain? – Santhosh Reddy May 11 '20 at 14:24
-
It's relevant but I gues it's less efficient than other answers... idk – Matthew Miles May 11 '20 at 15:01