paint-brush
Python Programming: Cloning or Copying a Listby@bumblebee
333 reads
333 reads

Python Programming: Cloning or Copying a List

by Sonia JessicaJuly 21st, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This article talks about the various ways to clone or copy a list in Python.

Company Mentioned

Mention Thumbnail
featured image - Python Programming: Cloning or Copying a List
Sonia Jessica HackerNoon profile picture

Hello readers!


I hope you must be familiar with Python, one of the most popular languages. Python is a high-level and object-oriented programming language. In this article, we will discuss how to copy or clone a list in Python.

What is a List?

A list is a sequence data type in Python. A list is mutable which means that the values can be modified in the list. A list is used to hold multiple items together. Unlike, C++, a list may contain heterogeneous elements also. By heterogenous, we mean a single list can hold values of different data types.

Some of the common list methods are discussed below:


  • len(): In order to determine the number of items a list may contain, we can use len() function:


  1. Syntax: len(myList)
  2. Parameter: myList: A Python list
  3. Return Type: It returns the length of the string


  • append(): This function is used to append an elemet to the end of the list.


  1. Syntax: myList.append(myElement)
  2. Parameter: myElement: The element to be added at the end of the list.


  • clear(): This function is used to clear all the elements from the list.


  1. Syntax: myList.clear()


  • count(): This method when used with a list determines the number of occurrences of a particular element.


  1. Syntax: myList.count(myElement)
  2. Parameters: myElement: It represents the element whose number of occurrences is to be determined.
  3. Return Type: Returns the number of occurrences of myElement in myList.


How to copy a list in Python?


Python provides us with numerous ways to copy or clone a list in Python. Although these methods are used to accomplish the same task because of different complexities the execution time is different. That is, some methods take lesser time as compared to other methods. These methods are discussed below in detail:


  1. Using Slice operator: This is the easiest and the fastest way to copy a list in Python. This method is quite useful when the programmer wants to modify the list but at the same time wants to maintain an original copy of the list. In this method a copy of the list is made and also a reference to the list is maintained. This procedure of copying a list through the slicing technique is also known as cloning.

    1. Execution Time: The executing time of this method is around 0.3 seconds.


  2. Using inbuilt list() method: Python provides us with an inbuilt list() method using which we can copy a list easily. This is the simplest method to copy a list as all we need is to call the inbuilt function. This function has the following syntax:

    1. Syntax: list(iterable)
    2. Parameter: iterable: an object that can be a collection of elements like a set, string, list etc.
    3. Return Type: A list containing iterable objects.
    4. Execution Time: The execution time of this method is around 0.075 seconds.


  1. Using inbuilt extend() method: The inbuilt extend() function can be used to copy a list into another. The syntax of this function is given below:

    1. Syntax: myList.extend(iterable)

    2. Parameter: iterable: an object that can be a collection of elements like a set, string, list etc.

    3. Return Type: Modifies the myList by copying elements from iterable at the end of myList.

    4. Execution Time: The execution time of this method is around 0.054 seconds.


  2. Using the list comprehension method: The list comprehension method is used to copy elements individually from one list to another. List comprehension provides us with the simplest and shortest way when we want to make a new list on the basis of an existing list.

    1. Execution Time: The execution time of this method is around 0.217 seconds.


  3. Using list append() method: In Python, we can use the inbuilt append() function to append elements to the end of a list. This function has the following syntax:

    1. Syntax: myList.append(element)

      Here, the element is an element that has to be appended at the end of the list.

    2. Execution Time: The execution time of this method is around 0.325 seconds.

      Therefore, we can iterate over the original list using a for-in loop and append each element of the list into another list one by one.


  4. Using copy() method: Python provides us with the inbuilt copy() method using which we can copy all the elements from one list to another.

    1. Execution Time: The execution time of this method is around 1.488 seconds.


  5. Using deep copy method: In the deep copy method, the process of copying takes place recursively. Firstly, a collection of objects is constructed based on the original list and then the child objects are copied and presented in the original list. In this method, a copy of objects is copied to other objects. Any change made to the copy doesn’t reflect back to the original list.

  1. Using shallow copy method: In the shallow copy method, a new collection object is constructed and then it is populated with references to the child objects. The recursion is not involved during the copying process therefore, copies of the child objects are not made. In this process, a reference of an object is copied to another object. In contrast to the deep copy method, any change made to the copied object gets reflected back to the original object.


    1. Example: We would now demonstrate various methods as discussed above:
    2. Source Code: Python program to demonstrate various methods to copy or clone a list in Python
Importing library

import copy                               # Statement 1

Function to copy a list using

the slice (:) operator

def copyListFunction1(myList):            # Statement 2
copiedList = myList[:]                # Statement 3
return copiedList                     # Statement 4

Function to copy a list using

the inbuilt list() function

def copyListFunction2(myList):            # Statement 5
copiedList = list(myList)             # Statement 6
return copiedList                     # Statement 7

Function to copy a list using

the inbuilt extend() function

def copyListFunction3(myList):            # Statement 8
copiedList = []                       # Statement 9
copiedList.extend(myList)             # Statement 10
return copiedList                     # Statement 11

Function to copy a list using

list comprehension technique

def copyListFunction4(myList):                          # Statement 12
copiedList = [element for element in myList]        # Statement 13
return copiedList                                   # Statement 14

Function to copy a list using

the inbuilt append function

def copyListFunction5(myList):                          # Statement 15
copiedList = []                                     # Statement 16
for element in myList:                              # Statement 17
copiedList.append(element)                      # Statement 18return copiedList                                   # Statement 19

Python program to copy a list

using the inbuilt copy() method

def copyListFunction6(myList):                          # Statement 20
copiedList = myList.copy()                          # Statement 21
return copiedList                                   # Statement 22

Python program to copy a list

using the deep copy method

def copyListFunction7(myList):                          # Statement 23
copiedList = copy.deepcopy(myList)                  # Statement 24
return copiedList                                   # Statement 25

Python program to copy a list

using the shallow copy() method

def copyListFunction8(myList):                          # Statement 26
copiedList = copy.copy(myList)                      # Statement 27
return copiedList                                   # Statement 28

Menu Driver Code

originalList = [2, 4, 8, 12, 14, 16]                    # Statement 29
copiedList1 = copyListFunction1(originalList)           # Statement 30
copiedList2 = copyListFunction2(originalList)           # Statement 31
copiedList3 = copyListFunction3(originalList)           # Statement 32
copiedList4 = copyListFunction4(originalList)           # Statement 33
copiedList5 = copyListFunction5(originalList)           # Statement 34
copiedList6 = copyListFunction6(originalList)           # Statement 35
copiedList7 = copyListFunction7(originalList)           # Statement 36
copiedList8 = copyListFunction8(originalList)           # Statement 37

print("Original List:", originalList)                   # Statement 38
print("Copied list 1:", copiedList1)                    # Statement 39
print("Copied list 2:", copiedList2)                    # Statement 40
print("Copied list 3:", copiedList3)                    # Statement 41
print("Copied list 4:", copiedList4)                    # Statement 42
print("Copied list 5:", copiedList5)                    # Statement 43
print("Copied list 6:", copiedList6)                    # Statement 44
print("Copied list 7:", copiedList7)                    # Statement 45
print("Copied list 8:", copiedList8)                    # Statement 46


Output:

Program Description:

  • In the program; statement 2, statement 5, statement 8, statement 12, statement 15, statement 20, statement 23 and statement 28 corresponds to copyListFunction1, copyListFunction2, copyListFunction3, copyListFunction4, copyListFunction5, copyListFunction6, copyListFunction7 an copyListFunction8 functions respectively.

  • Each of the functions is used to demonstrate the working of methods as discussed above.

  • copyListFunction1:

    • In this function, we have demonstrated how we can clone or copy a list using the slice operator method.
    • This function accepts the original list as a parameter, myList. Inside this function, we have declared a list, copiedList.
    • Using the slice operator, we are copying myList into copiedList.
    • Eventually, the function returns copiedList.
  • copyListFunction2:

    • In this function, we have demonstrated how we can clone or copy a list using the list() function.
    • This function also accepts the original list as a parameter, myList. Inside this function, we have declared a list, copiedList.
    • We are calling the inbuilt list() function by passing myList as an argument, the result has been stored in copiedList.
    • Eventually, the function returns copiedList.
  • copyListFunction3:

    • In this function, we have demonstrated how we can clone or copy a list using the extend() function.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we created an empty list, copiedList.
    • We are invoking the inbuilt extend() function on copiedList by passing myList as an argument.
    • Now, copiedList is the copied or cloned list.
    • Eventually, the function returns copiedList.
  • copyListFunction4:

    • In this function, we have demonstrated how we can clone or copy a list using the extend() function.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we created an empty list, copiedList.
    • We are invoking the inbuilt extend() function on copiedList by passing myList as an argument.
    • Now, copiedList is the copied or cloned list.
    • Eventually, the function returns copiedList.
  • copyListFunction5:

    • In this function, we have demonstrated how we can clone or copy a list with the help of the inbuilt append() function.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we have created an empty list, copiedList.
    • Now we are iterating over myList using the for-in loop and at each step of the iteration, we are invoking inbuilt append() function on copiedList by passing the current element of the list as an argument.
    • Now, copiedList is the copied or cloned list.
    • Eventually, the function returns copiedList.
  • copyListFunction6:

    • In this function, we have demonstrated how we can clone or copy a list using the inbuilt copy() function.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we have declared a list, copiedList.
    • We are invoking the inbuilt copy() function on myList and the result is the copied list that has been stored in the copiedList.
    • Now, copiedList is the copied or cloned list. Eventually, the function returns copiedList.
  • copyListFunction7:

    • In this function, we have demonstrated how we can clone or copy a list using the deep copy method.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we have declared a list, copiedList.
    • We are calling the copy.deepcopy() function by passing myList as an argument and the result has been stored in the copiedList.
    • Now, copiedList is the copied or cloned list. Eventually, the function returns copiedList.
  • copyListFunction8:

    • In this function, we have demonstrated how we can clone or copy a list using the shallow copy method.
    • This function also accepts the original list as a parameter, myList.
    • Inside this function, we have declared a list, copiedList.
    • We are calling the copy.copy() function by passing myList as an argument and the result has been stored in the copiedList.
    • Now copiedList is the copied or cloned list.
    • Eventually, the function returns copiedList.
  • In the menu driver code, we have initialized a list of integers, originalList. Then, we have called all the eight functions discussed above by passing originalList as an argument. To store results we have declared eight lists: copiedList1, copiedList2, copiedList3, copiedList4, copiedList5, copiedList6, copiedList7 and copiedList8.

  • Eventually, In statement 38 we are printing the original list to the console and from 39 to 46 we have printed copied lists obtained by using various methods.


Summary: Firstly, we started with understanding the basics of a list in Python. Then, we learnt about various ways to clone or copy a list in Python. Then, we saw how we can use these methods in practice. We also got a deep understanding of the entire program.


Congratulations! You have moved one more step forward in understanding lists in Python. I hope you enjoyed learning these methods and it will definitely help you to become a good programmer.