Dec-22-2020, 04:02 AM
When you repeatedly do
Then when you modify level1, all the copies inside are changed. If you want them independent, you need to make different copies.
level2.append(level1)
, you keep putting another copy of the same list into the outer list. Then when you modify level1, all the copies inside are changed. If you want them independent, you need to make different copies.
>>> inner = ["x"] >>> outer = [inner] >>> inner.append("z") # Modifies the object that is inside "outer" >>> outer [['x', 'z']]
>>> inner = ["x"] >>> outer = [inner[:]] # contents are a copy of inner, not the same object >>> inner.append("z") # modifies inner, but not the object in outer >>> inner ['x', 'z'] >>> outer [['x']]