7

Creating List of Empty List in Python

 3 years ago
source link: https://jdhao.github.io/2020/11/22/python_list_of_empty_list_pitfall/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Creating List of Empty List in Python

2020-11-22265 words 2 mins read 95 times read

I wrote some code for my project and found that the result isn’t correct. So I spent quite some time debugging the whole working process this program and found that it is because I have initialized a list wrongly.

When we do the following in Python:

x = [[]] * 3
x[0].append(1.0)

I expect x now becomes [[1.0], [], []]. Instead, it becomes [[1.0], [1.0], [1.0]]. This is because when we use multiplication to create x, we actually created 3 references to the empty list. List is a mutable object in Python. When we append values to a list, we haven’t changed its identity. As a result, changing either one of the 3 sub-list will change the others since they refer to the same list.

It is different when we create a list of same immutable objects. For example, if we create a list of same int, and then change one of the int, other elements will not change. It is because we can not change the value of immutable types, assigning a new int to a list element will make it point to another address.

In [18]: a = [1] * 2

In [19]: a
Out[19]: [1, 1]

In [20]: print(id(a[0]), id(a[1]))
4438635584 4438635584

In [21]: a[0] = 2

In [22]: print(id(a[0]), id(a[1]))
4438635616 4438635584

To create a list 3 empty lists, we may use list comprehension instead:

x = [[] for _ in range(3)]

In each iteration, a new empty list is created. So the 3 sub-list are independent of each other.

Author jdhao

LastMod 2020-11-22

License CC BY-NC-ND 4.0

Reward
Prev Next

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK