1

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?

asked Dec 13, 2015 at 0:43

3 Answers 3

4

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.

answered Dec 13, 2015 at 0:46

1 Comment

This is the fastest solution so far, especially noticeable the bigger your list is.
0

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)
[]
answered Dec 13, 2015 at 1:14

Comments

0

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.

answered Dec 13, 2015 at 1:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.