There are multiple ways to copy one list to another in Python. Here are a few commonly used methods:
- Using the slice operator
[:]
:
list1 = [1, 2, 3, 4, 5]
list2 = list1[:] # Copy list1 to list2
- Using the
copy()
method:
list1 = [1, 2, 3, 4, 5]
list2 = list1.copy() # Copy list1 to list2
or
list2 = list1.copy()
- Using the
list()
function:
list1 = [1, 2, 3, 4, 5]
list2 = list(list1) # Copy list1 to list2
- Using the
extend()
method:
list1 = [1, 2, 3, 4, 5]
list2 = []
list2.extend(list1) # Copy list1 to list2
- 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.
+ There are no comments
Add yours