How to Copy a List and Make Changes in Python?

Estimated read time 1 min read

When you want to make changes to a list while keeping the original list intact, you can create a copy of the list. Python provides multiple ways to copy a list. Here are a few methods:

  1. Using the slice operator [:]:
original_list = [1, 2, 3, 4, 5]
copy_list = original_list[:]
  1. Using the list() function:
original_list = [1, 2, 3, 4, 5]
copy_list = list(original_list)
  1. Using the copy() method from the copy module:
import copy

original_list = [1, 2, 3, 4, 5]
copy_list = copy.copy(original_list)

Once you have created a copy of the list, you can make changes to the copied list without affecting the original list. For example:

original_list = [1, 2, 3, 4, 5]
copy_list = original_list[:]

# Make changes to the copied list
copy_list.append(6)
copy_list.remove(3)

print("Original List:", original_list)
print("Copied List with Changes:", copy_list)

Output:

Original List: [1, 2, 3, 4, 5]
Copied List with Changes: [1, 2, 4, 5, 6]

In the example above, we create a copy of original_list using the slice operator [:]. Then, we make changes to the copy_list by appending a new element and removing an existing element. Finally, we print both the original list and the copied list with changes to verify that the original list remains unchanged.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply