The Wayback Machine - https://web.archive.org/web/20241013185242/https://www.geeksforgeeks.org/python-cloning-copying-list/
Open In App

Python | Cloning or Copying a list

Last Updated : 24 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will go through various ways of copy lists in Python. These various ways of copying list take different execution times, so we can compare them on the basis of time. 

Cloning or Copying a list

Below are the ways by which we can clone or copy a list in Python:

  • Using the slicing technique 
  • Using the extend() method 
  • List copy using =(assignment operator)
  • Using the method of Shallow Copy 
  • Using list comprehension 
  • Using the append() method 
  • Using the copy() method 
  • Using the method of Deep Copy
  • Using the map method 
  • Using slice() function

Copy or Clone a List Using Slicing Technique 

This is the easiest and fastest way to clone a list. This method is considered when we want to modify a list and also keep a copy of the original. In this, we make a copy of the list itself, along with the reference. This process is also called cloning. This technique takes about 0.039 seconds and is the fastest technique. In this example, we are using List Slicing Technique to clone or copy a list.

Python3




# Python program to copy or clone a list
# Using the Slice Operator
def Cloning(li1):
    li_copy = li1[:]
    return li_copy
 
 
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output: 

Original List: [4, 8, 2, 10, 15, 18] 
After Cloning: [4, 8, 2, 10, 15, 18] 

Time Complexity: O(n), where n is the length of slice
Auxiliary Space: O(1)

Clone or Copy Using Python extend() method 

The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete. In this example, we are using extend() to copy or clone list.

Python3




# Python code to clone or copy a list
# Using the in-built function extend()
 
 
def Cloning(li1):
    li_copy = []
    li_copy.extend(li1)
    return li_copy
 
 
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Python Copy List Using Assignment Operator

This is the simplest method of cloning a list by using = operators. This operator assigns the old list to the new list using Python operators. Here we will create a list and then we will copy the old list into the new list using assignment operators. In this example, we are using assignment operator to clone or copy Python list.

Python3




# Python code to clone or copy a list
# Using the List copy using =
def Cloning(li1):
    li_copy = li1
    return li_copy
   
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output: 

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Time Complexity: O(1)
Auxiliary Space: O(n), where n is length of list.

Using Shallow Copy in Python

This method of copying using copy. This takes around 0.186 seconds to complete. In this example, we are using Shallow Copy to copy or clone a list in Python.

Python3




# importing copy module
import copy
   
# initializing list 1
li1 = [1, 2, [3,5], 4]
   
# using copy for shallow copy 
li2 = copy.copy(li1)
 
print(li2)


Output:

[1, 2, [3, 5], 4]

Python Cloning or Copying a list Using List Comprehension 

In this example, we are using list comprehension to clone or copy a list.

Python3




# Python code to clone or copy a list
# Using list comprehension
def Cloning(li1):
    li_copy = [i for i in li1]
    return li_copy
   
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output: 

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Python append() to Clone or Copy a list

This can be used for appending and adding elements to list or copying them to a new list. It is used to add elements to the last position of the list. This takes around 0.325 seconds to complete and is the slowest method of cloning. In this example, we are using Python append to copy a Python list.

Python3




# Python code to clone or copy a list
# Using append()
def Cloning(li1):
    li_copy =[]
    for item in li1: li_copy.append(item)
    return li_copy
   
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output: 

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Using the copy() method 

The Python List copy() is an inbuilt method copy used to copy all the elements from one list to another. This takes around 1.488 seconds to complete.

Python3




# Python code to clone or copy a list
# Using built-in method copy()
def Cloning(li1):
    li_copy =[]
    li_copy = li1.copy()
    return li_copy
   
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)


Output: 

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Using the method of Deep Copy 

This method of copying is well explained in the article Deep Copy. This takes around 10.59 seconds to complete and is the slowest method of cloning.

Python3




# importing copy module
import copy
   
# initializing list 1
li1 = [1, 2, [3,5], 4]
 
# using deepcopy for deepcopy 
li3 = copy.deepcopy(li1)
print(li3)


Output:

[1, 2, [3, 5], 4]

Copy a List Using Enumerate Function

In this example, we are using enumerate function to copy or clone a list.

Python3




# Python code to clone or copy a list
# Using list comprehension
lst = [4, 8, 2, 10, 15, 18]
li_copy = [i for a,i in enumerate(lst)]
print("Original List:", lst)
print("After Cloning:", li_copy)


Output

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Python Copy or Clone a List using Map Function

In this example, we are using map function to clone or copy a list using map function.

Python3




# Python code to clone or copy a list
# Using map function
lst = [4, 8, 2, 10, 15, 18]
li_copy = map(int, lst)
print("Original List:", lst)
print("After Cloning:", *li_copy)


Output:

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: 4 8 2 10 15 18

Using slice() function

The Python slice() is an inbuilt method used to copy all the elements from one list to another. Here slice() function is passed with one argument which is an integer specifying at which position slicing will end.

Python3




# Python code to clone or copy a list
# Using slice() function
lst = [4, 8, 2, 10, 15, 18]
li_copy = lst[slice(len(lst))]
print("Original List:", lst)
print("After Cloning:", li_copy)
 
# This code is contributed by Pushpesh Raj.


Output

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Using the deque() function

The deque() function is used to create a double-ended queue in Python. It can be used to efficiently append or remove elements from both ends of the queue. In this approach, we create a deque object with the original list and then convert it back to a list to create a copy of the original list. 

Python3




from collections import deque
 
original_list = [4, 8, 2, 10, 15, 18]
 
copied_list = deque(original_list)
copied_list = list(copied_list)
 
print("Original List:", original_list)
 
print("After Cloning:", copied_list)


Output

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Copy a Python List Using reduce()

In this example, we are using reduce() method to copy a list.

Python3




from functools import reduce
 
def clone_list(li1):
    return reduce(lambda x, y: x + [y], li1, [])
 
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_list(li1)
print("Original List:", li1)
print("After Cloning:", li2)
#This code is contributed by Jyothi pinjala.


Output

Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

Time complexity : O(n), where n is the length of the input list.
Space complexity : O(n)



Previous Article
Next Article

Similar Reads

Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Array Copying in Python
Let us see how to copy arrays in Python. There are 3 ways to copy arrays : Simply using the assignment operator.Shallow CopyDeep CopyAssigning the ArrayWe can create a copy of an array by using the assignment operator (=). Syntax : new_arr = old_ arrIn Python, Assignment statements do not copy objects, they create bindings between a target and an o
4 min read
MoviePy – Shallow copying Video File Clip
In this article we will see how we can shallow copy the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the o
2 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Appending Item to Lists of list using List Comprehension | Python
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python | Check if all the values in a list that are greater than a given value
Given a list, print all the values in a list that are greater than the given value Examples: Input : list = [10, 20, 30, 40, 50] given value = 20 Output : No Input : list = [10, 20, 30, 40, 50] given value = 5 Output : YesMethod 1: Traversal of list By traversing in the list, we can compare every element and check if all the elements in the given l
4 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python Remove Duplicates from a List
The job is simple. We need to take a list, with duplicate elements in it and generate another list that only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplic
3 min read
Python | Largest, Smallest, Second Largest, Second Smallest in a List
Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. Moreover, the vast inbuilt functions of Python, make the task easier. So using these techniques, let's try to find the various ranges of the number in a given list. Examples: In
5 min read
Python | Sort a List according to the Length of the Elements
In this program, we need to accept a list and sort it based on the length of the elements present within. Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "a
4 min read
Python | Creating a 3D List
A 3-D List means that we need to make a list that has three parameters to it, i.e., (a x b x c), just like a 3 D array in other languages. In this program we will try to form a 3-D List with its content as "#". Lets look at these following examples: Input : 3 x 3 x 3 Output : [[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']], [['#', '#', '#'], [
4 min read
Count set bits using Python List comprehension
Write an efficient program to count number of 1s in binary representation of an integer. Examples: Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Practice Tags :