Home » Python : Copying Lists

Python : Copying Lists

Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

In Python, lists are mutable, meaning that you can change their contents after they are created. Sometimes, you may want to create a copy of a list to preserve the original list while working on the modified version.

Python offers several methods for copying lists, including shallow and deep copies.

In this tutorial, we will explore different ways to copy lists, understand the difference between shallow and deep copies, and work through practical examples.

 

1. Using the copy() Method

The copy() method creates a shallow copy of a list. This means that the copied list will contain references to the same objects as the original list, but the list itself is a new object.

Example: Copying a List Using copy()

# Example: Copying a list using copy()
original_list = [1, 2, 3, 4]

# Create a copy of the list
copied_list = original_list.copy()

# Modify the copied list
copied_list.append(5)

# Print both lists
print("Original list:", original_list)  # Output: [1, 2, 3, 4]
print("Copied list:", copied_list)      # Output: [1, 2, 3, 4, 5]

In this example:

original_list.copy() creates a shallow copy of the list. Modifying copied_list does not affect the original list.

2. Using the list() Constructor

The list() constructor can also be used to create a shallow copy of a list. It works similarly to the copy() method, creating a new list with the same elements.

Example: Copying a List Using list()

# Example: Copying a list using the list() constructor
original_list = [10, 20, 30]

# Create a copy of the list
copied_list = list(original_list)

# Modify the copied list
copied_list.append(40)

# Print both lists
print("Original list:", original_list)  # Output: [10, 20, 30]
print("Copied list:", copied_list)      # Output: [10, 20, 30, 40]

In this example:

list(original_list) creates a shallow copy of original_list. Modifications to copied_list do not affect the original list.

3. Using Slicing to Copy a List

You can create a shallow copy of a list using slicing ([:]). This technique creates a new list with the same elements as the original list.

Example: Copying a List Using Slicing

# Example: Copying a list using slicing
original_list = ['a', 'b', 'c']

# Create a copy of the list using slicing
copied_list = original_list[:]

# Modify the copied list
copied_list.append('d')

# Print both lists
print("Original list:", original_list)  # Output: ['a', 'b', 'c']
print("Copied list:", copied_list)      # Output: ['a', 'b', 'c', 'd']

In this example:

original_list[:] creates a shallow copy of the list. Modifying the copy does not affect the original list.

4. Using copy.deepcopy() for Deep Copies

If a list contains mutable objects (like other lists), and you want to copy both the outer list and the objects inside it, you need to perform a deep copy using the copy module’s deepcopy() function.

A shallow copy only copies the outer list, while a deep copy creates independent copies of the elements inside the list.

Example: Deep Copy of a List with Nested Lists

import copy

# Example: Deep copy of a list with nested lists
original_list = [[1, 2], [3, 4]]

# Create a deep copy of the list
copied_list = copy.deepcopy(original_list)

# Modify the copied list
copied_list[0].append(3)

# Print both lists
print("Original list:", original_list)  # Output: [[1, 2], [3, 4]]
print("Copied list:", copied_list)      # Output: [[1, 2, 3], [3, 4]]

In this example:

copy.deepcopy() creates a deep copy of the list. Changes made to the nested list in copied_list do not affect the nested lists in original_list.

5. Using a Loop to Copy a List

You can copy a list manually using a loop. This method iterates through the elements of the original list and appends each element to a new list.

Example: Copying a List Using a Loop

# Example: Copying a list using a loop
original_list = [1, 2, 3]
copied_list = []

# Manually copy each element
for item in original_list:
    copied_list.append(item)

# Modify the copied list
copied_list.append(4)

# Print both lists
print("Original list:", original_list)  # Output: [1, 2, 3]
print("Copied list:", copied_list)      # Output: [1, 2, 3, 4]

In this example:

The loop iterates through original_list, and each element is added to copied_list. Modifying the copied list does not affect the original list.

6. Using List Comprehension to Copy a List

List comprehension provides a concise way to copy a list. It is similar to using a loop but in a single line of code.

Example: Copying a List Using List Comprehension

# Example: Copying a list using list comprehension
original_list = [5, 6, 7]

# Create a copy of the list using list comprehension
copied_list = [item for item in original_list]

# Modify the copied list
copied_list.append(8)

# Print both lists
print("Original list:", original_list)  # Output: [5, 6, 7]
print("Copied list:", copied_list)      # Output: [5, 6, 7, 8]

In this example:

List comprehension is used to create a shallow copy of original_list. Changes to the copied list do not affect the original list.

7. Comparing the Original and Copied Lists

When copying a list, you may want to check whether the contents of the original list and the copied list are the same and whether they refer to the same object in memory.

Example: Checking Equality and Identity

# Example: Comparing lists after copying
original_list = [1, 2, 3]
copied_list = original_list.copy()

# Check if the lists have the same contents (equality)
print(original_list == copied_list)  # Output: True

# Check if the lists are the same object in memory (identity)
print(original_list is copied_list)  # Output: False

In this example:

original_list == copied_list checks if the two lists have the same elements (True).
original_list is copied_list checks if the two lists are the same object in memory (False).

8. Shallow Copy vs. Deep Copy

A shallow copy creates a new list, but the elements inside the list are still references to the original objects. This means that if the list contains mutable objects (like other lists), changes to the objects inside the copied list will reflect in the original list.

A deep copy, on the other hand, creates a new list and recursively copies all objects inside it, ensuring that changes to the copied list and its contents do not affect the original list.

Example: Shallow Copy of a List Containing Mutable Objects

# Example: Shallow copy of a list containing a list
original_list = [[1, 2], [3, 4]]

# Create a shallow copy using copy()
copied_list = original_list.copy()

# Modify the nested list in the copied list
copied_list[0].append(3)

# Print both lists
print("Original list:", original_list)  # Output: [[1, 2, 3], [3, 4]]
print("Copied list:", copied_list)      # Output: [[1, 2, 3], [3, 4]]

In this example:

Shallow copy shares references to the nested lists. Therefore, modifying the nested list in copied_list affects the nested list in original_list.

Example: Deep Copy of a List Containing Mutable Objects

import copy

# Example: Deep copy of a list containing a list
original_list = [[1, 2], [3, 4]]

# Create a deep copy using deepcopy()
copied_list = copy.deepcopy(original_list)

# Modify the nested list in the copied list
copied_list[0].append(3)

# Print both lists
print("Original list:", original_list)  # Output: [[1, 2], [3, 4]]
print("Copied list:", copied_list)      # Output: [[1, 2, 3], [3, 4]]

In this example:

Deep copy ensures that modifications to copied_list do not affect the original list.

Summary

You can create a shallow copy of a list using the copy() method, the list() constructor, or slicing ([:]).
Deep copy can be achieved using the copy.deepcopy() function, which is useful for copying lists containing mutable objects like other lists.
You can manually copy a list using loops or list comprehension.
Shallow copies share references to the objects inside the list, while deep copies create independent copies of the objects inside the list.
You can check the equality (==) and identity (is) of the original and copied lists to verify their contents and whether they refer to the same object in memory.

By mastering these techniques for copying lists in Python, you can preserve the original data and avoid unintended side effects when modifying lists in your programs.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More