Nope
Nope

Reputation: 35990

Python: List initialization differences

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.

Upvotes: 3

Views: 7721

Answers (3)

rob
rob

Reputation: 37644

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.

Upvotes: 1

oggy
oggy

Reputation: 3571

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.

Upvotes: 16

Juergen
Juergen

Reputation: 12728

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.

Upvotes: 3

Related Questions