What is the best way to copy a list?

This question already has an answer here:

  • How to clone or copy a list? 18 answers

  • If you want a shallow copy (elements aren't copied) use:

    lst2=lst1[:]
    

    If you want to make a deep copy then use the copy module:

    import copy
    lst2=copy.deepcopy(lst1)
    

    I often use:

    lst2 = lst1 * 1
    

    If lst1 it contains other containers (like other lists) you should use deepcopy from the copy lib as shown by Mark.


    UPDATE: Explaining deepcopy

    >>> a = range(5)
    >>> b = a*1
    >>> a,b
    ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
    >>> a[2] = 55 
    >>> a,b
    ([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])
    

    As you may see only a changed... I'll try now with a list of lists

    >>> 
    >>> a = [range(i,i+3) for i in range(3)]
    >>> a
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
    >>> b = a*1
    >>> a,b
    ([[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[0, 1, 2], [1, 2, 3], [2, 3, 4]])
    

    Not so readable, let me print it with a for:

    >>> for i in (a,b): print i   
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
    >>> a[1].append('appended')
    >>> for i in (a,b): print i
    
    [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
    [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
    

    You see that? It appended to the b[1] too, so b[1] and a[1] are the very same object. Now try it with deepcopy

    >>> from copy import deepcopy
    >>> b = deepcopy(a)
    >>> a[0].append('again...')
    >>> for i in (a,b): print i
    
    [[0, 1, 2, 'again...'], [1, 2, 3, 'appended'], [2, 3, 4]]
    [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
    

    你也可以这样做:

    a = [1, 2, 3]
    b = list(a)
    
    链接地址: http://www.djcxy.com/p/79360.html

    上一篇: 复制一个类,C#

    下一篇: 什么是复制列表的最佳方式?