0

How is the property of lists(Case 1) called that lets the output of print y be different from Case 2?

# Case 1: using a list as value
>>> x = ["one", "two", "three"]
>>> y = x
>>> x[0] = "four"
>>> print x
["four", "two", "three"]
>>> print y
["four", "two", "three"]

# Case 2: using an integer as value
>>> x = 3
>>> y = x
>>> x = x + 1
>>> print x
4
>>> print y
3

Edit:

To show that this behavior has nothing to do with lists being mutable and strings not, instead of Case 2, the following case could have been given instead:

>>> x = ["one", "two", "three"]
>>> y = x
>>> x = x + ["four", "five"]
>>> print x
["four", "two", "three", "four", "five"]
>>> print y
["four", "two", "three"]
Bentley4
  • 10,678
  • 25
  • 83
  • 134
  • 4
    Please make the title of your question readable. Avoid putting code in there, better try to summarize your question. – Ivaylo Strandjev Jun 20 '13 at 13:50
  • 2
    What _would_ be a good title for this question, if someone doesn't know about references vs. values? – Reinstate Monica -- notmaynard Jun 20 '13 at 13:56
  • Exactly, if you don't know the name of the property how would you explain it Ivaylo? – Bentley4 Jun 20 '13 at 13:57
  • About the change someone made in the title: it may be easier to read but it's less descriptive. I don't really see this as an improvement. If someone had the same question as me, I don't see how that title would ever lead him to this thread. So the question will be easily duplicated again. – Bentley4 Jun 20 '13 at 16:51

1 Answers1

2

The key difference between two snippets is

>>> x[0] = "four"

vs

>>> x = x + 1

In the first case, you modify an existing object, in the second you create a new one. So the first snippet has one object and two names, x and y, referring to it, in the second snippet there are two objects. Note that this has nothing to do with mutability of lists (and immutability of ints), you could have written the second snippet as

x = [1,2,3]
y = x 
x = x + [4]

and get essentially the same result (=two distinct objects).

georg
  • 211,518
  • 52
  • 313
  • 390