Reputation: 12
When I run this code, output is 11, but my expected output is 10.
a=[10]
b=a
b[0]=11
print(a)
What's the issue? And how do I get my expected output without importing any external module?
Upvotes: 0
Views: 37
Reputation: 3121
It's because b
is a reference to a
. Changing any element of a
or b
are affecting the whole a
and b
list. To keep the list a
always the same, Copy a
to b
then changing won't affect to a
.
a = [10]
b = a.copy() # Also can slice it by b = a[:]
b[0] = 11
print(a)
Upvotes: 1