Table of Contents
show
Creating a copy of the same list of elements with two different memory locations is called cloning
Changes in one list will not affect locations of another list
Cloning is a process of making a copy of the list without modifying the original list
- Slicing
- list( )
- copy( )
Copying the list using slice operator
orig_list = [10,1,2,7,5]
new_list = orig_list[:]
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)
Output
Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]
Copying the list using list( ) method
orig_list = [10,1,2,7,5]
new_list = list(orig_list)
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)
Output
Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]
Copying the list using copy( ) method
orig_list = [10,1,2,7,5]
new_list = orig_list.copy()
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)
Output
Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]
Views: 0