0

Background

Consider the following code:

list_of_lists = [[]] * 5
list_of_lists[2].append(123)
print(list_of_lists)

I would expect the result to be

[[], [], [123], [], []]

But instead the result is

[[123], [123], [123], [123], [123]]

Clearly, the [[]] * 5 creates a list of 5 of the same object, so any reference to one of them, is a reference to all of them.

Question

How do I circumvent this? Can I append something to one of the lists in a list?

Alec
  • 1,986
  • 4
  • 23
  • 47
  • 1
    Use: `list_of_lists = [[] for _ in range(5)]` – mozway Aug 14 '22 at 21:13
  • _How do I circumvent this?_ Multiplying the inner list causes the identical references. So, use some method other than multiplication. For example `list_of_lists = [[], [], [], [], []]` – John Gordon Aug 14 '22 at 21:17

1 Answers1

1

Your current list_of_lists is a list of five references to a single list, so there is no such thing as "one of them" that you could append to without affecting the "others" (there are no others -- it's just one list with five names). To create a list of five references to five lists, do:

list_of_lists = [[] for _ in range(5)]

Each time the expression [] is evaluated, a list is created. The difference is that in [[]] * 5 the inner [] is only being evaluated once (and then the outer list is being multiplied, which does not entail any sort of copying of the values within the list), whereas in [[] for _ in range(5)] the inner [] is being evaluated once per iteration of for _ in range(5).

Samwise
  • 68,105
  • 3
  • 30
  • 44