Solving problem is about exposing yourself to as many situations as possible like Copying nested lists in Python and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Copying nested lists in Python, which can be followed any time. Take easy to follow this discuss.
I want to copy a 2D list, so that if I modify one list, the other is not modified.
For a one-dimensional list, I just do this:
a = [1, 2] b = a[:]
And now if I modify
a is not modified.
But this doesn’t work for a two-dimensional list:
a = [[1, 2],[3, 4]] b = a[:]
If I modify
a gets modified as well.
How do I fix this?
For a more general solution that works regardless of the number of dimensions, use
import copy b = copy.deepcopy(a)
b = [x[:] for x in a]