4

In Python, if I write:

a = [1]
b = 3 * [a]
a.append(2)
print a, b

Then, the output is:

[1, 2] [[1, 2], [1, 2], [1, 2]]

However, when I write:

a = [1]
b = 3 * a # notice the missing brackets here 
a.append(2)
print a, b

This turns out to be:

[1, 2] [1, 1, 1]

What is going on here?

Remolten
  • 2,614
  • 2
  • 25
  • 29
QuestionEverything
  • 4,809
  • 7
  • 42
  • 61
  • 1
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – e4c5 Jun 02 '17 at 13:48

2 Answers2

3

In the first example, think of what Python does to this statement:

b = 3 * [a]

It becomes:

b = [[a], [a], [a]]

Thus, changing a will be reflected in b, because b is constituted of a objects.

However, in the second example, you do this:

b = 3 * a

This creates a copy of list a, and is equivalent to:

b = [1, 1, 1]

Thus, when appending to a this time, nothing is changed.

Remolten
  • 2,614
  • 2
  • 25
  • 29
  • I understand when we say `b = [a]` , both b and a point to the same references. same is the case when we give `b = a`. So why does it behave differently ONLY when a "*" operator with an `int` is applied on `a` e.g `b = 3 * a`. could you please explain this as well. TIA – DineshKumar Jun 02 '17 at 14:34
  • When you do `b = 3 * a` it creates 3 copies of `a` (in this case `1`), and places them into a list. As for why, I couldn't tell you. I'm sure it has something to do with the language design, but I'm not knowledgable enough about the subject to give a definite answer. – Remolten Jun 02 '17 at 14:37
1

This is because when you do b = 3 * [a], the reference to variable a is not lost. Thus, any change made in a will be replicated in b.

However, when you run b = 3 * a a new list instance is being created, which has no reference to the a list anymore.

All data structures in Python are objects, and the variables point to them. :)

Zev Averbach
  • 1,044
  • 1
  • 11
  • 25