Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'append' mutates all elements in a list? [duplicate]

Tags:

python

list

I am building a list of lists. I am reading the elements from an input file. I am reading in each line in the file as a string-single-element to a sub-list in the list. First, I created the list of lists:

>>> b = [[]] * 5

However, when I tried to append an item, I got the following:

>>> b[1].append("abc")
>>> b
[ ['abc'], ['abc'], ['abc'], ['abc'], ['abc'])

Why does append change all the sub-lists? Is insert() better in this situation?

like image 498
Concerned_Citizen Avatar asked Jan 11 '23 13:01

Concerned_Citizen


1 Answers

When you do [[]] * 5 it is a list of same objects (empty lists here) repeated 5 times.

You can check it by:

>>> b = [[]] *5

>>> b
[[], [], [], [], []]

>>> id(b[0])
140588316211896

>>> id(b[1])
140588316211896

What you would need to do is:

>>> b = [[] for i in range(5)]
>>> b[0].append('abc')
>>> b
[['abc'], [], [], [], []]

In case of [[] for i in range(5)], in each loop a new empty list object is created.

And insert would not be a good option here because insert is a O(n) operation whereas appending would be O(1).

like image 141
Ankur Ankan Avatar answered Jan 20 '23 00:01

Ankur Ankan