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
  • 11,032
  • 11
  • 64
  • 119

1 Answers1

0

Use

f = [[] for _ in range(3)]
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
grapes
  • 8,185
  • 1
  • 19
  • 31
  • @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