0
>>> f = [[]] * 3
[[], [], []]
>>> f[0].append(1)
[[1], [1], [1]]

I think [[]] * x creates a list of x lists, but each inner list is the same object so changing one inner list changes all the others.

How can I quickly initialise a list of lists, but have each inner list be unique?

I want

>>> f = something
[[], [], []]
>>> f[0].append(1)
[[1], [], []]
theonlygusti
  • 9,142
  • 8
  • 49
  • 93

1 Answers1

0

Use

f = [[] for _ in range(3)]
theonlygusti
  • 9,142
  • 8
  • 49
  • 93
grapes
  • 7,391
  • 1
  • 15
  • 30
  • @theonlygusti, is there a difference in behavior between `for x` and `for _` or it is a notification that name wont be used? – grapes Dec 04 '18 at 14:16
  • traditionally `_` is a throwaway variable. Means its value won't be used. https://stackoverflow.com/a/47599668/3310334 – theonlygusti Dec 04 '18 at 14:39