5

TIL python list variable asignment points to the original instance

I know this isn't reddit but today I noticed that in python when you asign a list variable to another variable in python, any change to the new variable affects the original one. To copy one you could asign a slice or use methods returning the list:

l = [1,2,3,4]
l2 = l
l2.append(5)
print(l)
#Outputs [1,2,3,4,5]

l3 = list(l2) # also works with l2[:]
l3.append(6)
print("l2 = ", l2, "\nl3 = ", l3)
#Outputs l2 = [1,2,3,4,5]
# l3 = [1,2,3,4,5,6]

I wonder how the fuck I haven't encountered any bug when using lists while doing this. I guess I'm lucky I haven't used lists that way (which is strange, I know). I guess I still have a long way to go.

Comments
  • 4
    Welcome to just a small part if the weirdness of Python. Just be glad it's not as weird as JavaScript.
  • 2
    Kind of programming 101, don't see how that's weird :(
  • 0
    @novopl I thought it worked the same for all built-in types, but turns out it's just numbers and tuples. I've read the python documentation a TON but don't recall reading anything about this.
  • 0
    So what's the point of copying to a new variable and iterating over that to modify it then? Won't that be the same as just modifying the list I'm iterating through? Which isn't exactly ideal either.
  • 1
    @TheCapeGreek @TheCapeGreek you're copying the reference to a variable, not the variable "data". If you want to copy a list in python, you would do:

    a = [1,2,3,4]
    b = a[:]

    Now 'b' is a completely new list and modifying it won't change 'a'. You also have a 'copy' module to do just that. Some languages provide something like a .copy() or .clone() method to do that.
Add Comment