Open In App

Python List copy() Method

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The list Copy() method makes a new shallow copy of a list.

Example

Python3




# Using list fruits
fruits = ["mango","apple","strawberry"]
# creating a copy shakes
shakes = fruits.copy()
# printing shakes list
print(shakes)


Output

['mango', 'apple', 'strawberry']

What is List Copy() Method?

The list Copy() function in Python is used to create a copy of a list. There are two main ways to create a copy of the list Shallow copy and Deep copy. We will discuss the list copy() method in detail below.

The list copy() function is used to create a copy of a list, which can be used to work and it will not affect the values in the original list. This gives freedom to manipulate data without worrying about data loss.

List copy() Method Syntax

list.copy()

Parameters

  • The copy() method doesn’t take any parameters.

Returns: Returns a shallow copy of a list. 

Note: A shallow copy means any modification in the new list won’t be reflected in the original list. 

How to Create a Simple Copy of a List in Python

Copying and creating a new list can be done using copy() function in Python.

Python3




# Using List girls
girls = ["Priya","Neha","Radha","Nami"]
# Creating new copy
girlstudent = girls.copy()
#printing new list
print(girlstudent)


Output

['Priya', 'Neha', 'Radha', 'Nami']

More Examples on List copy() Method

Let us see a few examples of the list copy() method.

Example 1: Simple List Copy

In this example, we are creating a List of Python strings and we are using copy() method to copy the list to another variable.

Python3




lis = ['Geeks','for','Geeks']
new_list = lis.copy()
print('Copied List:', new_list)


Output

Copied List: ['Geeks', 'for', 'Geeks']

Example 2: Demonstrating the working of List copy() 

Here we will create a Python list and then create a shallow copy using the copy() function. Then we will append a value to the copied list to check if copying a list using copy() method affects the original list.

Python3




# Initializing list
lis1 = [ 1, 2, 3, 4 ]
 
# Using copy() to create a shallow copy
lis2 = lis1.copy()
 
# Printing new list
print ("The new list created is : " + str(lis2))
 
# Adding new element to new list
lis2.append(5)
 
# Printing lists after adding new element
# No change in old list
print ("The new list after adding new element : \
" + str(lis2))
print ("The old list after adding new element to new list  : \
" + str(lis1))


Output

The new list created is : [1, 2, 3, 4]
The new list after adding new element : [1, 2, 3, 4, 5]
The old list after adding new element to new list  : [1, 2, 3, 4]

Note: A shallow copy means if we modify any of the nested list elements, changes are reflected in both lists as they point to the same reference.

Shallow Copy and Deep Copy

A deep copy is a copy of a list, where we add an element in any of the lists, only that list is modified. 

In list copy() method, changes made to the copied list are not reflected in the original list. The changes made to one list are not reflected on other lists except for in nested elements (like a list within a list).

We can use the copy.deepcopy() from the copy module to avoid this problem.

  • Techniques to deep copy: 
    • Using copy.deepcopy()
  • Techniques to shallow copy: 
    • Using copy.copy()
    • Using list.copy()
    • Using slicing

To gain a deeper understanding, Refer to this article on Deep Copy vs Shallow Copy

Demonstrating Techniques of Shallow and Deep copy  

Here we will create a list and then create a shallow copy using the assignment operator, list copy() method, and copy.copy() method of the Python copy module.

We also create a deep copy using deepcopy() in Python. Then we will make changes to the original list and see if the other lists are affected or not.

Python3




import copy
 
# Initializing list
list1 = [ 1, [2, 3] , 4 ]
print("list 1 before modification:\n", list1)
 
# all changes are reflected
list2 = list1
 
# shallow copy - changes to
# nested list is reflected,
# same as copy.copy(), slicing
 
list3 = list1.copy()
 
# deep copy - no change is reflected
list4 = copy.deepcopy(list1)
 
list1.append(5)
list1[1][1] = 999
 
print("list 1 after modification:\n", list1)
print("list 2 after modification:\n", list2)
print("list 3 after modification:\n", list3)
print("list 4 after modification:\n", list4)


Output

list 1 before modification:
 [1, [2, 3], 4]
list 1 after modification:
 [1, [2, 999], 4, 5]
list 2 after modification:
 [1, [2, 999], 4, 5]
list 3 after modification:
 [1, [2, 999], 4]
list 4 after mo...

Copy List Using Slicing

Here we are copying the list using the list slicing method [:] and we are appending the ‘a’ to the new_list. After printing we can see the newly appended character ‘a’ is not appended to the old list.

Python3




list = [2,4,6]
new_list = list[:]
new_list.append('a')
print('Old List:', list)
print('New List:', new_list)


Output

Old List: [2, 4, 6]
New List: [2, 4, 6, 'a']

We discussed the definition, syntax and examples of list copy() method. copy() function is very useful when working with sensitive data and you can’t risk mistakes.

We also briefly talked about shallow vs deep copy. Hope this helped you in understanding copy() function in Python.

Read Other Python List Methods

More articles on to list copy:



Previous Article
Next Article

Similar Reads

copy in Python (Deep Copy and Shallow Copy)
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create "real copies" or "clones" of these objects, we can use the copy module in Python. Syntax of Python DeepcopySyntax:
5 min read
NumPy ndarray.copy() Method | Make Copy of a Array
The ndarray.copy() method returns a copy of the array. It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array. Example C/C++ Code # Python program explaining # numpy.ndarray.copy() function import numpy as geek x
2 min read
Copy a Python Dictionary and only Edit the Copy
Copying a dictionary in Python to preserve the original while making changes to the duplicate is a common task. Developers use methods like the `copy` module or the dictionary's `copy()` method to create an independent duplicate, allowing for isolated edits. This article explores commonly used techniques to copy a dictionary and modify only the dup
4 min read
Python Dictionary Copy Vs Deep Copy
In Python, Dictionary like other non-primitive data structures can be copied using various methods. The key distinction lies in the depth of the copy. In this article, we are going to learn about deep copy and shallow copy in Python. What is Shallow Copy in Python Dictionary?In Python, a shallow copy creates a new object that references the same un
3 min read
Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Python | How to copy a nested list
Copying a nested list in Python involves preserving both the structure and values of the original. One common method is using copy.deepcopy() from the copy module. Additionally, list comprehensions with slicing offer a concise approach for creating an independent duplicate. In the previous article, we have seen how to clone or Copy a list, now let'
4 min read
Copy List Python Without Reference
In Python, It is common knowledge that when we assign a list to another variable, we are creating a reference to the original list. But how to create a copy of the list without referencing the original. In this article, we will study different approaches by which we can create a copy of the list without referencing the original list. Copy List With
3 min read
Python | shutil.copy() method
C/C++ Code # Python program to explain shutil.copy() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied su
5 min read
Python PIL | copy() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.copy() method copies the image to another image object, this method is useful when we need to copy the image but also retain the original. Syntax:Image.copy() Parameters: no arguments Returns:An image object # Importing Image module fr
1 min read