0
Why do nested list behave like this?
10 Respuestas
+ 3
Oh, sorry, missed that point
It's because the code you use generates references to first element. Changing the first element will change all others too
+ 3
The reason for that behavior is that lists are created to look much simplied than they actually are. Like you might see lists, they could be collections of items, but the actual value that is used when the list is referred is just an address to the list, the list self is actually stored somewhere else.
When you multiplied the list [[0]]*4 you created 4 identical list addresses that all referred to the same list.
+ 3
The issue is in the way you create the nested lists. x=[[0]]*4 means the very same empty list is repeated 4 times. In other jargon, the nested empty lists are pointers to the same (empty list) object. If you change the first nested list, they all change because they're all the same object.
Try creating your nested list using the statement x=[[0] for i in range(4)]. This way you have 4 different nested empty lists and you can change one and keep the others different.
+ 3
* with lists is seemingly working with referring to the same one object again and again.
This is no problem with immutable objects like strings or numbers, because you don't need to care if internally ten times 0 in a list are in reality only one 0 or not.
It becomes different when you have a mutable object ten times in that list. Because in reality, it's not ten lists, but ten 'adress cards' to always the same list.
So if you fill a 5 into that one list, then all the adress cards will point to that 5.
So you have to make sure that you actually create a separate list each time. ChrAs method does the job:
'Please create a list with a 0 in it, and do that 4 times.'
+ 2
Try
a=[[0] for _ in range(4)]
a[0][0] = 9
print(a)
instead
0
You can think list as an object that can store other objects. Because lists are objects self, list can also contain other lists.
0
You did not get my point! I assign only one element of the list to be 9, why do others change?
0
Hi Ahmad Javanbakhti
What if you try thinking of lists as vectors holding e.g. scalar values. List of lists as matrix containing rows and columns. And list of lists of lists as some cubical arranged thing.
Hope this helps. Cheers. C
0
I understand the concept of nested lists. Why all the elements change to 9?
0
Thank you guys.