How to Copy One List to Another in Python?

Estimated read time 1 min read

There are multiple ways to copy one list to another in Python. Here are a few commonly used methods:

  1. Using the slice operator [:]:
list1 = [1, 2, 3, 4, 5]
list2 = list1[:]  # Copy list1 to list2
  1. Using the copy() method:
list1 = [1, 2, 3, 4, 5]
list2 = list1.copy()  # Copy list1 to list2

or

list2 = list1.copy()
  1. Using the list() function:
list1 = [1, 2, 3, 4, 5]
list2 = list(list1)  # Copy list1 to list2
  1. Using the extend() method:
list1 = [1, 2, 3, 4, 5]
list2 = []
list2.extend(list1)  # Copy list1 to list2
  1. Using list comprehension:
list1 = [1, 2, 3, 4, 5]
list2 = [x for x in list1]  # Copy list1 to list2

All of these methods create a new list (list2) that is a copy of the original list (list1). Modifying one list will not affect the other list. Choose the method that suits your specific use case and coding style.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply