a = [0,0]
b = a
a[0] = 1
print(b)
This code returns [1,0]
Shouldn't it return [0,0]?
Is there any way to bypass this bug/feature? (to have it return [0,0])
I probably have used code very similar to this in the past, there weren't any problems before...
a = [0,0]
b = a
a[0] = 1
print(b)
This code returns [1,0]
Shouldn't it return [0,0]?
Is there any way to bypass this bug/feature? (to have it return [0,0])
I probably have used code very similar to this in the past, there weren't any problems before...
Share Improve this question edited Feb 21 at 2:18 wjandrea 33.2k10 gold badges69 silver badges98 bronze badges asked Jan 30 at 19:37 Allen LanAllen Lan 11 bronze badge 2- 4 Not a bug. See How do I clone a list so that it doesn't change unexpectedly after assignment? – Guy Incognito Commented Jan 30 at 19:41
- 1 See Facts and muths about python names and values – Ahmed AEK Commented Jan 30 at 19:48
1 Answer
Reset to default 1this is not a bug, it's how Python handles mutable objects like lists.
since b
is assigned to a
, both variables point to the same list in memory. Changing a
affects b
because there is only one list.
you can use a.copy()
,this creates a new list with the same values
a = [0,0]
b = a.copy()
a[0] = 1
print(b)
Other methods mentioned in this answer