Table of Contents
ToggleCopying a list in Python refers to creating a new list that contains the same elements as the original list. This guide explains different methods for copying lists, including shallow copy, deep copy, and using slice notation, the list() function, and the copy() function.
A shallow copy creates a new object but copies only the references to the original elements. If the elements are mutable, changes made to them in the copied list will affect the original list.
import copy
# Original list
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Creating a shallow copy
shallow_copied_list = copy.copy(original_list)
# Modifying an element in the shallow copied list
shallow_copied_list[0][0] = 100
# Printing both lists
print("Original List:", original_list)
print("Shallow Copied List:", shallow_copied_list)
Output:
Original List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
Shallow Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
A deep copy creates a completely new object and recursively copies all the objects referenced by the original object. Changes made to the copied list do not affect the original list.
import copy
# Original list
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Creating a deep copy
deep_copied_list = copy.deepcopy(original_list)
# Modifying an element in the deep copied list
deep_copied_list[0][0] = 100
# Printing both lists
print("Original List:", original_list)
print("Deep Copied List:", deep_copied_list)
Output:
Original List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Deep Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
Slice notation [start:end:step] can be used to create a copy of a list by specifying the entire range of indices.
# Original list
original_list = [1, 2, 3, 4, 5]
# Copying the list using slice notation
copied_list = original_list[:]
# Modifying the copied list
copied_list[0] = 100
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)
Output:
Original List: [1, 2, 3, 4, 5]
Copied List: [100, 2, 3, 4, 5]
The list() function creates a new list object containing the same elements as the original list.
# Original list
original_list = [1, 2, 3, 4, 5]
# Copying the list using the list() function
copied_list = list(original_list)
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)
Output:
Original List: [1, 2, 3, 4, 5]
Copied List: [1, 2, 3, 4, 5]
The copy() function from the copy module creates a shallow copy of a list.
import copy
# Original list
original_list = [1, 2, 3, 4, 5]
# Copying the list using the copy() function
copied_list = copy.copy(original_list)
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)
Output:
Original List: [1, 2, 3, 4, 5]
Copied List: [1, 2, 3, 4, 5]
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now