89DEVs

Python List copy()

Python List copy()

The copy() method in copies a list and returns a shallow copy of the original list. A shallow copy means the new list contains references of nested objects to the original list. If the original list is changed the change appears in the copied list as well. To prevent this, use the deepcopy() method of the copy module.

copy a list using copy()

How to copy a list in Python? Use the copy() method as shown below to copy a list. # copy a list in python list1 = [1, 2, 3] list2 = list1.copy() print(list1) print(list2) In this example, the variable list1 is a list that contains the three integer values 1, 2 and 3. Then, the copy() method is used to copy list1 to list2. Finally, both lists are printed and the results are shown below. As we see, the lists contain the same elements, list2 is a copy of list1. [1, 2, 3] [1, 2, 3]

copy a list without using copy()

Instead of using the copy() method, it is possible to copy a list by assigning it to a new variable. An example is shown below. # copy a list without using copy() list1 = [1, 2, 3] list2 = list1 print(list1) print(list2) The variable list1 contains a list of the three integer values 1, 2 and 3. Then list1 is assigned to list2, which creates a shallow copy of the original list. Both lists are printed and contain the same elements, all three integer values. [1, 2, 3] [1, 2, 3]

Syntax of List copy()

The syntax of the copy method is: list2 = list1.copy()

Arguments of List copy()

The copy() method in Python does not except arguments. If any argument is passed, a TypeError exception is raised. TypeError: list.copy() takes no arguments (1 given)

Return value of List copy()

The copy() method returns a new list, which can be assigned to a variable. The original list is not modified or deleted, it remains untouched.

                
        

Summary


Click to jump to section