Jul-04-2021, 10:24 AM
Dear all,
I am new to Python, and currently I am practicing around a bit with lists. One of the assignments is to create a 3D list. Below is the code I use to create this 3D lists. I consists of some for-loops that create a list of lists. The output after the first print statement looks valid. If I request the value of a single element of the list, say lst[1][1][1], then it gives me a single value of 0 which is what I would expect. However, when I assign the entry lst[1][1][1] a different value, lst[1][1][1] = 4, it not only updates the element in lst[1][1][1], but it updates multiple entries of the list. I would expect that it only assigns the entry lst[1][1][1] the value 4, while leaving the other entries unaffected. What am I missing here?
PS. I know that there are more elegant methods to create a 3D list (list comprehension), but I am more interested in the behavior of lists than an elegant solution.
I am new to Python, and currently I am practicing around a bit with lists. One of the assignments is to create a 3D list. Below is the code I use to create this 3D lists. I consists of some for-loops that create a list of lists. The output after the first print statement looks valid. If I request the value of a single element of the list, say lst[1][1][1], then it gives me a single value of 0 which is what I would expect. However, when I assign the entry lst[1][1][1] a different value, lst[1][1][1] = 4, it not only updates the element in lst[1][1][1], but it updates multiple entries of the list. I would expect that it only assigns the entry lst[1][1][1] the value 4, while leaving the other entries unaffected. What am I missing here?
PS. I know that there are more elegant methods to create a 3D list (list comprehension), but I am more interested in the behavior of lists than an elegant solution.
# define variables for dimensions a = 3 b = 5 c = 8 # create two lists with zeros lst_dim2 = [0]*b lst_dim3 = [0]*c # create 3D list lst = [0]*a for i in range(a): lst[i] = lst_dim2 for j in range(b): lst[i][j] = lst_dim3 # print the list print(lst) # assign value to element of list lst[1][1][1] = 4 # print list after element assignment print(lst)