Skip to content
Advertisement

Why list.append() in Python changes every item in the original list?

I have this piece of code:

JavaScript

The output of this code:

JavaScript

The output I was expected:

JavaScript

How to get the expected output?

Advertisement

Answer

When you modify j and subsequently append it to the l, it’s a reference to the same dict that you append. Here is one way to operate on copies:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement