Jun 22, 2018

Five ways to clone or copy a list in python

Image: 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

import copy
newList = copy.copy(oldList)

This is a little slower than becauselist() has to find out the datatype of oldList

Method 5: Using deepcopy() function

import copy
new_list = copy.deepcopy(old_list)

This method is used if the list contains objects and that you want to copy as well.

Leave a Reply :


Comments :

Be the first, to comment!