-1
In [33]: x=[[]]*6

In [34]: x

Out[34]: [[], [], [], [], [], []]

In [35]: x[0]

Out[35]: []

In [36]: x[0].append(1)

In [37]: x

Out[37]: [[1], [1], [1], [1], [1], [1]]

I just append 1 to x[0], but why do all lists in the list x change?

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57

1 Answers1

0

This happens because x is a list of references to the same inner list.

To create a list of 6 different empty lists, you can use list comprehension:

a = [[] for _ in range(6)]
Phydeaux
  • 2,795
  • 3
  • 17
  • 35