0

Suppose I have a string called s1, and make a new string called s2 that is equal to s1. When I make any changes to s2, s1 remains unaffected.

However, I've found that this is not the case for lists. If I make a new list l2 from a pre-existing list l1, and make a change to l2, l1 is also changed.

Why is this the case?

Here's some sample code, in case I wasn't clear above.

s1 = "hello"
s2 = s1

s2 += " from the other side"

print (s1)
print (s2)

This will print "hello" and "hello from the other side". However, when we do something similar with lists:

l1 = ["Hello"]
l2 = l1

l2 += ["from the other side"]

print(l1)
print(l2)

It prints ["hello", "from the other side"] for BOTH l1 and l2.

Why do lists and strings behave differently in this case?

  • 1
    There is a big difference: lists are mutable and strings are immutable. `s2 += ...` does not actually modify the original string, it creates a new string object and binds the name `s2` to that new object. – wim Dec 08 '15 at 19:18
  • @wim the real gotcha here IMHO is that `+=` for lists doesn't actually (re)bind the name to a new value, but is equivalent to `list.extend()`. – Lukas Graf Dec 08 '15 at 19:29

0 Answers0