+ 4

Python Question

In this code (in the output), why is b[0] not equal to 3, but b[1][1] equal to 5? a=[1,[2,3]] b=a[:] a[0]=3 a[1][1]=5 print(b)---->b=[1,[2,5]

26th Apr 2024, 6:37 PM
Mohammadamin
Mohammadamin - avatar
4 Respuestas
+ 4
a = [1, [2, 3]] print(f"a = {a}") # Output: a = [1, [2, 3]] b = a[:] print(f"b = {b}") # Output: b = [1, [2, 3]] a[0] = 3 print(f"a = {a}") # Output: a = [3, [2, 3]] a[1][1] = 5 print(f"a = {a}") # Output: a = [3, [2, 5]] print(f"b = {b}") # Output: b = [1, [2, 5]] b[0] = 3 print(f"b = {b}") # Output: b = [3, [2, 5]] So working through this it appears that 'b' shares references only to the nested list with 'a' So b is still its own list. So you have to target the first interger of b to change it. References to help explain it better. https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-list-slicing/ Python Shallow Copy and Deep Copy In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. https://www.programiz.com/python-programming/shallow-deep-copy
26th Apr 2024, 8:08 PM
Chris Coder
Chris Coder - avatar
+ 4
# Mohammadamin, when slicing, a new list is created, while the old list remains unchanged, respectively, object b receives its data storage address, but retains the cell addresses of the built-in list of object a. # That is, if you change the second value in list b in the second cell, then it will also change in list a...😎: a=[1,[2,3]] b=a[:] a[0]=3 b[1][1]=5 print(a) # [3,[2,5]] print(b) # [1,[2,5]]
26th Apr 2024, 10:51 PM
Solo
Solo - avatar
+ 3
I found this, let me know if any thing so far has been helpful. https://www.sololearn.com/Discuss/2801058/?ref=app
27th Apr 2024, 3:36 AM
Chris Coder
Chris Coder - avatar
+ 1
a = [1, [2, 3]] b = a[:] # Shallow copy of list a a[0] = 3 # Modify the first element of a a[1][1] = 5 # Modify the second element of the list within a print(b) # Output: [1, [2, 5]]
28th Apr 2024, 7:41 AM
Suhani Kewat