0

It seems there is an unexpected behavior regarding lists with Python 3.8.1:

    > l = [[]] * 4
    > l[0].append(1)
    > l
    [[1], [1], [1], [1]]

I would expect l to be equal to [[1], [], [], []].

Should not the lists inside l correspond to different "objects"?

On the other side the following code behaves as expected.

    > l = [ [] for i in range(4)]
    > l[0].append(1)
    > l
    [[1], [], [], []]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • 2
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Sergey Ronin Jan 07 '20 at 18:42

1 Answers1

2

This is built in behavior. When multiplying lists in such fashion, you're not creating new lists, but just copying the references to one initial list, therefore the modification of one of the items leads to others being modified.

See: List of lists changes reflected across sublists unexpectedly

As you've found, the recommended method to circumvent this issue is by using a list comprehension.

Sergey Ronin
  • 756
  • 7
  • 23