0

I'm coming from a JavaScript background and this might be why lists in Python feel a bit weird to me. Can someone explain to me how this piece of code works and how i'm getting this to work the way i want?

a = [0,0]
b = a
a[0] = a[0]+1   #somehow manipulates b as well
print a         #i want this line to return [1,0]
print b         #i want this line to return [0,0], not [1,0]

I know there are lists and tuples (which are immutable), but this knowledge somehow didn't help me any further.

Help is appreciated. :)

Jonas Bergner
  • 1,663
  • 4
  • 15
  • 22
  • 3
    Typical answer: the list is **not copied**: `a` and `b` **refer to the same list**. Use `b = list(a)` to copy the list. – Willem Van Onsem Feb 15 '17 at 11:40
  • 2
    `a` and `b` are names for objects. They name the same `list` object. – Peter Wood Feb 15 '17 at 11:41
  • 1
    You've not made a copy with `b = a`, it's only creating a new label pointing to the same object. That's because the list is mutable. If `a = 3` (immutable int) then `b = a` would result in both pointing to separate `3` values. To create a copy of a list use: `b = a[:]` – otocan Feb 15 '17 at 11:45
  • 4
    @otocan: That explanation is wrong. `a = 3` and `b = a` still have them point to the same `3` value, it's just that being immutable, it doesn't matter that they refer to the same value; anything that changes them (e.g. `a += 1` will rebind `a` and leave `b` unchanged). – ShadowRanger Feb 15 '17 at 11:52
  • 1
    @ShadowRanger - thanks for the lesson. Leaving my comment up to give yours context. – otocan Feb 15 '17 at 11:56
  • @otocan I think it would be better to delete the comment as it's misleading, especially so since someone has upvoted it. – Peter Wood Feb 15 '17 at 22:43

0 Answers0