0

Apologies for the rather ambiguous title, but I couldn't think of a better way to put it. In Python, I can initialize empty lists or other variables like:

>>> a, b, c = [[]] * 3
>>> d, e, f = [0] * 3

I noticed that if I initialize the empty lists like this, then they are all connected so when I do:

>>> a.append(3)

The element 3 is also appended to lists b and c.

What is the reason for this behavior? Also, what is this style of initialization called? Thanks.

Sean
  • 2,890
  • 8
  • 36
  • 78
  • 3
    That's not several empty lists; that's three references to *one* list. – user2357112 Jan 22 '20 at 04:45
  • Three variables so declared are pointing to the same memory space. You are trying to append items in one variable but the variable points to memory where all the other variables points. https://www.python-course.eu/python3_deep_copy.php – dipesh Jan 22 '20 at 04:48
  • @dipesh you mean object, not variables. – juanpa.arrivillaga Jan 22 '20 at 05:05
  • @juanpa.arrivillaga yeah, my mistake :) – dipesh Jan 22 '20 at 05:06
  • 1
    Because `n*[x]` always creates a list with `n` references to whatever `x` is. That's just the semantics of the repetition operator, `*`. I've never seen code like this: `d, e, f = [0] * 3` and honestly, this just strikes me as unidiomatic and sloppy, and if I were going to do that I'd just do `d, e, f = 0`. – juanpa.arrivillaga Jan 22 '20 at 05:07

1 Answers1

0

In your code, all variables refer to the same empty list! , so change in one variable will be reflected across all. Refer this for more info.

You can check it, this way id(a) == id(b) == id(c) it will return True.

Try the code below,

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

a.append(3)
print(a, b, c)

OR

a, b, c = [[] for i in range(3)]

a.append(3)
print(a, b, c)

Output

([3], [], [])
Shibiraj
  • 769
  • 4
  • 9