Python Copy List

Document 对象参考手册Python3 Examples

Define a list and copy the elements of that list to another list.

Example 1

def clone_example(li1):
    li_copy = li1[:]
    return li_copy
 
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_example(li1)
print("Original list:", li1)
print("Copied list:", li2)

The output of the above example is:

原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Example 2: Using the extend() method

def clone_example(li1):
    li_copy = []
    li_copy.extend(li1)
    return li_copy
 
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_example(li1)
print("Original list:", li1)
print("Copied list:", li2)

The output of the above example is:

原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Example 3: Using the list() method

def clone_example(li1):
    li_copy = list(li1)
    return li_copy
 
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_example(li1)
print("Original list:", li1)
print("Copied list:", li2)

The output of the above example is:

原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Document 对象参考手册Python3 Examples

Other Extensions