Copying nested lists in Python

Posted on

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.

Copying nested lists in Python

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 b, a is not modified.

But this doesn’t work for a two-dimensional list:

a = [[1, 2],[3, 4]]
b = a[:]

If I modify b, a gets modified as well.

How do I fix this?

Answer #1:

For a more general solution that works regardless of the number of dimensions, use copy.deepcopy():

import copy
b = copy.deepcopy(a)
Answered By: Ayman Hourieh

Answer #2:

b = [x[:] for x in a]
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.