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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With