There are several methods one can use to copy or clone a list I am discussing a few with you:-
1. Using the extend() method
We can copy one list into another using the extend() function. This function appends each element of the iterable object e.g. another list to the end of the new list and it takes around 0.053 seconds to process.
Example:
# To clone a copy list Python can be used
# Using the in-built function extend()
defCloning(li1):
li_copy =[]
li_copy.extend(li1)
returnli_copy
# Driver Code
li1 =[1,2,3,4,5,6]
li2 =Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
which gives the output
Original list: [1,2,3,4,5,6]
After cloning: [1,2,3,4,5,6]
2.Using list comprehension
This method is useful when one needs to copy all the elements individually from one list to another and takes around 0.217 seconds to process
Example:
# To clone a copy list Python can be used
# Using list comprehension
defCloning(li1):
li_copy =[i fori inli1]
returnli_copy
# Driver Code
li1 =[1,2,3,4,5,6]
li2 =Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
The output of the code will be
Original List: [1,2,3,4,5,6]
After Clooning:[1,2,3,4,5,6}
3. Using slicing technique
When we want to modify a list and also keep a copy of the original we will use this method, this method is also fastest and easiest way to clone a list. This method just takes around 0.039 seconds to complete and considered as the fastest method.
Example:
# To clone a copy list Python can be used
# Using the in-built function extend()
defCloning(li1):
li_copy =[]
li_copy.extend(li1)
returnli_copy
# Driver Code
li1 =[1,2,3,4,5,6]
li2 =Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
The output of the code will be
Original List: [1,2,3,4,5,6]
After Cloning: [1,2,3,4,5,6]
I hope this will help you with your query.
Be a Python Expert. Enroll in Python Programming Course by Intellipaat