1
a = [1,2,3,4]
b = a
b[0] = 10
print a

I haven't touched the numbers in list a, but they still change. Why does this happen? Also, this seems to return the expected result:

a = [1,2,3,4]
b = a[:]
b[0] = 10
print a

Can somebody tell me what [:] does and why the first code changes a?

Junha Lee
  • 33
  • 4

1 Answers1

1

Python doesn't have variables in the traditional sense. When you create something with a = [1, 2, 3, 4] you are just creating a new "tag" a that points to that list.

So b = a is just creating a new tag named b that points to the same list. If you alter b, you alter a.

In your second example, b = a[:], [:] is "slicing" the list which, in this case, would return all the values of the list, thus b now points to it's own copy of [1, 2, 3, 4], rather than a's copy.

If you were to do something like b = a[1:3] you could get a better idea of what the slice operator does.