5. Copying Method in a List
Python provides different ways to copy the contents of one list to another. These methods create a new list with the same elements, without modifying the original list.
1. copy()
The copy()
method creates a shallow copy of the list.
It means a new list is created with the same elements, but changes to one list
won't
affect the other.
Syntax:
new_list = original_list.copy()
Example:
students = ['Devanshi', 'Mukesh', 'Angel']
copied_list = students.copy()
copied_list.append('Simran') # Modify copied list
print("Original List:", students)
print("Copied List:", copied_list)
Output:
Original List: ['Devanshi', 'Mukesh', 'Angel']
Copied List: ['Devanshi', 'Mukesh', 'Angel', 'Simran']
Explanation:
-
The
copy()
method creates a new list that contains the same elements as the original list. -
When you make changes in the
copied_list
(like adding or removing elements), the originalstudents
list remains unchanged. -
This proves that both
students
andcopied_list
are stored in different memory locations. So they are independent of each other.
Summary:
copy()
method is used to create a duplicate list with the same elements.- It performs a shallow copy – means the new list has same values, but at a different memory location.
- Changes made to the copied list do not affect the original list.
- It is useful when you want to work with the same data without changing the original list.