Cloning a List in Python
In this section, we will learn how to copy the elements of one list to another list.
Example 1: Using Slicing
def clone_list(li1): li_copy = li1[:] return li_copy li1 = [4, 8, 2, 10, 15, 18] li2 = clone_list(li1) print("Original list:", li1) print("Copied list:", li2)
Output:
Original list: [4, 8, 2, 10, 15, 18] Copied list: [4, 8, 2, 10, 15, 18]
In this example, we use slicing ([:]
) to create a shallow copy of the original list.
Example 2: Using extend()
Method
def clone_list(li1): li_copy = [] li_copy.extend(li1) return li_copy li1 = [4, 8, 2, 10, 15, 18] li2 = clone_list(li1) print("Original list:", li1) print("Copied list:", li2)
Output:
Original list: [4, 8, 2, 10, 15, 18] Copied list: [4, 8, 2, 10, 15, 18]
In this example, we use the extend()
method to add elements from the original list to a new list.
Example 3: Using list()
Method
def clone_list(li1): li_copy = list(li1) return li_copy li1 = [4, 8, 2, 10, 15, 18] li2 = clone_list(li1) print("Original list:", li1) print("Copied list:", li2)
Output:
Original list: [4, 8, 2, 10, 15, 18] Copied list: [4, 8, 2, 10, 15, 18]
In this example, we use the list()
constructor to create a copy of the original list.