In Python, assigning one list to another using = does not create a new copy. It only creates a new reference to the same list in memory. To avoid accidentally changing the original list, you need to create an explicit copy using:
copy() methodlist() constructor[:]copy.deepcopy() for nested (multidimensional) listsb = a points b to the same list as a.When you write:
a = [1, 2, 3]
b = a
Both a and b refer to the same list in memory. Changing one will affect the other.
To avoid this, you use a copying technique:
copy(), list(), and slicing [:] create a new list with the same elements.copy.deepcopy() recursively copies nested lists so that inner lists are independent.The simplest and most readable way to copy a list is by using the copy() method.
fruits = ["apple", "banana", "cherry"]
copy_list = fruits.copy()
print(copy_list)
You can also pass an existing list to the list() constructor to create a new list.
fruits = ["apple", "banana", "cherry"]
copy_list = list(fruits)
print(copy_list)
Slicing with [:] returns a shallow copy of the list.
fruits = ["apple", "banana", "cherry"]
copy_list = fruits[:]
print(copy_list)
For nested lists (lists inside lists), a shallow copy is not enough. Use copy.deepcopy() to make a full independent copy.
import copy
nested = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested)
nested[0][0] = 99
print("Original:", nested)
print("Deep copy:", deep_copy)
For the simple copy examples, the output will be a new list with the same elements:
["apple", "banana", "cherry"]
In the deep copy example, you modify nested after creating deep_copy. The printed result will look like:
Original: [[99, 2], [3, 4]]
Deep copy: [[1, 2], [3, 4]]
This shows that the deep copy is completely independent: changes in nested do not affect deep_copy.
copy() or slicing [:] for simple, non-nested lists.deepcopy() when working with nested or multidimensional lists.= does not copy a list; it only assigns a new reference.original_list and copied_list for clarity.[:] and print both lists.copy() method to duplicate a list of strings, then modify the copy and observe the original.[[1, 2], [3, 4]]) and test the difference between a shallow copy and a deep copy.