Python: list initialization differences

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

list_1 = [0] * 10

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

Are there more efficient ways to accomplish this same task?

Thanks in advance.

+3
source share
3 answers

It depends on whether your list items are mutable, if any, there will 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 may be a difference in performance between them, but I'm not sure which one will run faster.

+15
source

, , , , .

. , - - .

.

+3

The first of them is not only faster, but also more readable: just by looking quickly, you will immediately understand what is in this list, and in the second case you need to stop and see the iteration.

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

+1
source

Source: https://habr.com/ru/post/1713071/


All Articles