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...
this 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