Copying nested lists in Python

后端 未结 2 1734
悲&欢浪女
悲&欢浪女 2020-11-22 13:32

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[:]


        
相关标签:
2条回答
  • 2020-11-22 13:46

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

    import copy
    b = copy.deepcopy(a)
    
    0 讨论(0)
  • 2020-11-22 13:52
    b = [x[:] for x in a]
    
    0 讨论(0)
提交回复
热议问题