It is quite a silly question, but I am really confused. Please have a look my code:
>>> my_list = [1, 2, 3]
>>> my_list_new = my_list[:]
>>> my_list_new[0] = 100
>>> my_list_new
[100, 2, 3]
>>> my_list
[1, 2, 3]
So it works as it should. I copied my_list
. When I changed the my_list_new
- only one list changed.
Now look here:
>>> my_list2 = [[1, 2, 3], [4, 5, 6]]
>>> my_list_new2 = my_list2[:]
>>> my_list_new2[0][0] = 100
>>> my_list_new2
[[100, 2, 3], [4, 5, 6]]
>>> my_list2
[[100, 2, 3], [4, 5, 6]]
As you can see I changed my_list_new2
, but both lists changed. Is it normal Python behaviour for nested lists? How to avoid it?