If I have list a = [1, 2, 3]
the sum of this list is 6. I want to transform a to iterate through it so that a = [1,1,1,1,1,1]
.
Best way to do this?
3 Answers 3
You can sum the elements and create a new list with the result:
>>> a = [1, 2, 3]
>>> a = [1] * sum(a)
>>> a
[1, 1, 1, 1, 1, 1]
This is efficient compared to solutions using iteration because only one memory allocation is needed. Growing a list in an iteration involves multiple memory allocations if your list has reasonable size.
1 Comment
Another way is to use itertools.repeat
, should be more efficient(if the sum of a is very very huge, the list for b will be very huge if you directly generate all the items, but in this way we use iterator, don't worry.), note that you can use it for only once.
>>> from itertools import repeat
>>> a = [1, 2, 3]
>>> b = repeat(1, sum(a))
>>> type(b)
<type 'itertools.repeat'>
>>> list(b)
[1, 1, 1, 1, 1, 1]
>>> list(b)
[]
Comments
Another solution using itertools
that only traverses the original list once.
>>> import itertools
>>> a = [1, 2, 3]
>>> [1 for i in itertools.chain.from_iterable(map(range, a))]
[1, 1, 1, 1, 1, 1]
The range construct inside the generator expression is often found in a function named flatten
.
It is probably needlessly complicated for creating a list but when used in a for
loop, it allows for fully lazy evaluation, which could be useful.