0

could someone explain why this thing exists and how to counteract it

a = [1, 2, 3]
b = a
b[1] = 0
print(a)
a = [1, 0, 3]

Its bugging me, because, when I use this with int, then it acts normally.

a = 1
b = a
b +=1
print(a)
a = 1

It`s really messing with some of my code
Thanks in advance

petezurich
  • 9,280
  • 9
  • 43
  • 57

2 Answers2

1

By doing b = a you are having both point to the same spot in memory. Thus, changes to one will reflect in the other.

A simple fix to copy an array without them being connected:

b = a[:]
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
0

b = a is making b a reference to the same list as a. Use

b = a.copy()

to make a separate list.

Kraigolas
  • 5,121
  • 3
  • 12
  • 37