Apr-30-2024, 05:13 PM
You can initialise a list containing 3 zeroes as follows:
mylist = 3*[0]
If you initialise a list containing 4 of such lists as follows:
mylist = 4*[3*[0]]
you get the following list of lists:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Now try to assign a value to the first element of the first list as follows:
mylist[0][0] = 1
When you print mylist you get:
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
Why is the value duplicatied 4 times?
I don't understand this.
If you define exactiy the same list by writing it out:
mylist2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
mylist2 looks the same as mylist initially. But now you can assign elements without the duplication.
It seems as if Pyhon creates a list of three items under water and creates the outer list as 4 references to this list.
Is there a way to avoid this without having to spell things out?
mylist = 3*[0]
If you initialise a list containing 4 of such lists as follows:
mylist = 4*[3*[0]]
you get the following list of lists:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Now try to assign a value to the first element of the first list as follows:
mylist[0][0] = 1
When you print mylist you get:
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
Why is the value duplicatied 4 times?
I don't understand this.
If you define exactiy the same list by writing it out:
mylist2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
mylist2 looks the same as mylist initially. But now you can assign elements without the duplication.
It seems as if Pyhon creates a list of three items under water and creates the outer list as 4 references to this list.
Is there a way to avoid this without having to spell things out?