1

What happened when I wrote a, b, c = [[],] * 3 in python?
It seems that a, b, c are the same object.

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

The answer is [1,2] , why?

Adelin
  • 7,809
  • 5
  • 37
  • 65
Yinwen Cai
  • 13
  • 2

1 Answers1

-2

The * operator just creates copies of the same list [] three times, not three fresh lists.

So, a, b, c all point to the same list. And you added 1 and 2 to both.


This:

a, b, c = [[] for _ in range(3)]
a.append(1)
b.append(2)
print(c)

would give you [] as expected.

Saswat Padhi
  • 6,044
  • 4
  • 20
  • 25