0
>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0]
[]  
>>> a[0].append([1,2])
>>> a
[[[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]], [[1, 2]]]
>>> b = [[] for _ in range(10)]
>>> b
[[], [], [], [], [], [], [], [], [], []]
>>> b[0].append([1,2])
>>> b
[[[1, 2]], [], [], [], [], [], [], [], [], []]

Why the first nested list('a') append list at every index? What I'm missing here?

CosmicOppai
  • 59
  • 1
  • 9
  • 1
    When you initiate a variable using something like `[[]]*10`, the machine assigns the same location to each of these empty brackets. This means, that any change to one of these objects, would change all of them. – TheFaultInOurStars May 18 '22 at 13:22
  • You have (the reference to) the same inner list 10 times your outer list. List references "point" to data - same references to the same data. `[[] for _ in range(10)]` creates 10 different lists. Use `print(*map(id,a))` & `print(*map(id,b))` to see what ids the inner elements got. – Patrick Artner May 18 '22 at 13:23

0 Answers0