Copying nested lists in Python

38,684

Solution 1

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

import copy
b = copy.deepcopy(a)

Solution 2

b = [x[:] for x in a]
Share:
38,684
SuperString
Author by

SuperString

Hello World!

Updated on July 01, 2022

Comments

  • SuperString
    SuperString almost 2 years

    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?