Five ways to clone or copy a list in python
Python is a very flexible language. It provides more that one way to do a task. Copying in python is pretty easy and can be done in many ways. The following ways can be used not only for copying list, for other built-in data types as well.
Method 1: Copy the reference
newList = oldList
The new list gets modified whenever old_list gets updated. Check out the cons of using this method.
Method 2: Using slicing
newList = oldList[:]
The slicing of the list returns another list object which gets copied to newList.
Method 3: Using list()
newList = list(oldList)
This method creates a list object from the iterable oldList.
Method 4: Using copy() function
newList = copy.copy(oldList)
This is a little slower than because
list() has to find out the datatype of
Method 5: Using deepcopy() function
new_list = copy.deepcopy(old_list)
This method is used if the list contains objects and that you want to copy as well.