3

I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?

list_1 = [0] * 10

list_2 = [0 for i in range(10)]

Are there any better ways to do this same task?

Thanks in advance.

3 Answers 3

16

It depends on whether your list elements are mutable, if they are, there'll be a difference:

>>> l = [[]] * 10
>>> l
[[], [], [], [], [], [], [], [], [], []]
>>> l[0].append(1)
>>> l
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
>>> l = [[] for i in range(10)]
>>> l[0].append(1)
>>> l
[[1], [], [], [], [], [], [], [], [], []]

For immutable elements, the behavior of the two is the same. There might be a performance difference between them, but I'm not sure which one would perform faster.

Sign up to request clarification or add additional context in comments.

7 Comments

>>> import timeit >>> timeit.timeit("[0] * 10") 0.5434829189135002 >>> timeit.timeit("[0 for i in range(10)]") 1.7427103316054815
difference increases with the length of a list
@SilentGhost: Thanks, that seams to validate my statements.
@oggy: Very interesting, but the "things" should be either strings or number -- both are immutable.
@SilentGhost: nice, I suspected so but was too lazy to test. Also unsurprisingly, using xrange instead of range (in Python 2) somewhat improves the performance of the list comprehension, but not dramatically.
|
3

I personally would advice to use the first method, since it is most likely the best performing one, since the system knows in advance the size of the list and the contents.

In the second form, it must first evaluate the generator and collect all the values. Most likely by building up the list incrementally -- what is costly because of resizing.

The first method should also be the best way at all.

1 Comment

That advice is conferred by the profiling result in the Comment by SilentGhost to the post by oggy.
1

The first one is not only faster, but is also more readable: just by a quick look, you immediately understand what's into that list, while in the second case you have to stop and see the iteration.

Since source code is written once and read many times, for immutable elements I definitely vote for the first option.

Comments

Your Answer

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.