Home » Python: Copying Arrays Tutorial with Examples

Python: Copying Arrays Tutorial with Examples

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

In Python, copying arrays (or lists, as Python does not have a built-in array type like other languages) is a common operation when you want to duplicate a list for further modifications without altering the original.

Python provides several ways to copy arrays, each with its own advantages and considerations, especially when dealing with shallow vs. deep copies.

In this tutorial, we will cover:

  1. What is an Array (List) in Python?
  2. Shallow vs. Deep Copy
  3. Copying Arrays Using Assignment
  4. Copying Arrays Using copy() Method
  5. Copying Arrays Using List Slicing
  6. Copying Arrays Using the list() Function
  7. Copying Arrays Using copy Module (Deep Copy)
  8. Examples and Common Use Cases

Let’s explore each method of copying arrays with examples and explanations.

1. What is an Array (List) in Python?

In Python, the most common way to store a collection of elements is by using a list. Lists are mutable sequences, meaning their elements can be changed.

Python does not have a built-in array data structure, but lists can be used in a similar way to arrays in other programming languages.

Example of a List (Array):

my_list = [1, 2, 3, 4, 5]
print(my_list)  # Output: [1, 2, 3, 4, 5]

You can store any type of elements in a list, including numbers, strings, and even other lists.

2. Shallow vs. Deep Copy

Before diving into the methods of copying arrays, it's important to understand the difference between shallow copies and deep copies.

  • Shallow Copy: A shallow copy creates a new list, but it does not create new copies of the objects contained within the original list. For simple lists (e.g., lists of numbers or strings), a shallow copy behaves as expected. However, if the list contains mutable objects (like other lists), changes made to those mutable objects will be reflected in both the original and the copied list.
  • Deep Copy: A deep copy creates a completely independent copy of the original list and any objects contained within it. Changes made to the copied list do not affect the original, and vice versa.

3. Copying Arrays Using Assignment

The simplest way to “copy” a list is by using assignment. However, this does not create a new list; it only creates a new reference to the same list. Changes made to one list will affect the other.

Example: Copying a List Using Assignment

original_list = [1, 2, 3]
copied_list = original_list  # This is not a true copy

copied_list[0] = 99
print("Original list:", original_list)  # Output: [99, 2, 3]
print("Copied list:", copied_list)      # Output: [99, 2, 3]
  • In this example, modifying copied_list also modifies original_list because they refer to the same list.

4. Copying Arrays Using copy() Method

The copy() method creates a shallow copy of a list. It is the most straightforward way to duplicate a list in Python.

Example: Copying a List Using copy()

original_list = [1, 2, 3]
copied_list = original_list.copy()

copied_list[0] = 99
print("Original list:", original_list)  # Output: [1, 2, 3]
print("Copied list:", copied_list)      # Output: [99, 2, 3]
  • In this example, changes to copied_list do not affect original_list because they are separate lists.

5. Copying Arrays Using List Slicing

List slicing is another way to create a shallow copy of a list. The syntax list[:] creates a copy of the entire list.

Example: Copying a List Using Slicing

original_list = [1, 2, 3]
copied_list = original_list[:]

copied_list[0] = 99
print("Original list:", original_list)  # Output: [1, 2, 3]
print("Copied list:", copied_list)      # Output: [99, 2, 3]
  • In this example, slicing creates a new list, so changes made to copied_list do not affect original_list.

6. Copying Arrays Using the list() Function

The list() function can be used to create a new list from an existing iterable, such as a list. This also creates a shallow copy of the list.

Example: Copying a List Using list()

original_list = [1, 2, 3]
copied_list = list(original_list)

copied_list[0] = 99
print("Original list:", original_list)  # Output: [1, 2, 3]
print("Copied list:", copied_list)      # Output: [99, 2, 3]
  • In this example, using list() creates a new list, and changes to copied_list do not affect original_list.

7. Copying Arrays Using copy Module (Deep Copy)

When working with nested lists or lists containing other mutable objects, you may want to create a deep copy. The copy module provides a deepcopy() function that creates an independent copy of the original list and all objects contained within it.

Example: Deep Copying a Nested List Using deepcopy()

import copy

original_list = [[1, 2], [3, 4]]
copied_list = copy.deepcopy(original_list)

copied_list[0][0] = 99
print("Original list:", original_list)  # Output: [[1, 2], [3, 4]]
print("Copied list:", copied_list)      # Output: [[99, 2], [3, 4]]
  • In this example, deepcopy() creates a completely independent copy of original_list. Changes to copied_list do not affect original_list, even for nested lists.

8. Examples and Common Use Cases

Example 1: Copying a Simple List

original_list = [10, 20, 30]

# Copy using different methods
copied_list1 = original_list.copy()
copied_list2 = original_list[:]
copied_list3 = list(original_list)

# Modify the copied list
copied_list1[0] = 100

# Output the results
print("Original list:", original_list)  # Output: [10, 20, 30]
print("Copied list 1:", copied_list1)   # Output: [100, 20, 30]
  • In this example, different methods are used to copy the list. All create a shallow copy.

Example 2: Copying a Nested List (Shallow vs. Deep Copy)

import copy

# Nested list
original_list = [[1, 2], [3, 4]]

# Shallow copy
shallow_copy = original_list.copy()

# Deep copy
deep_copy = copy.deepcopy(original_list)

# Modify the shallow copy
shallow_copy[0][0] = 99

# Modify the deep copy
deep_copy[1][1] = 88

# Output the results
print("Original list:", original_list)  # Output: [[99, 2], [3, 4]]
print("Shallow copy:", shallow_copy)    # Output: [[99, 2], [3, 4]]
print("Deep copy:", deep_copy)          # Output: [[1, 2], [3, 88]]
  • In this example, the shallow copy affects the original nested list, while the deep copy does not.

Example 3: Copying a List of Strings (Shallow Copy)

fruits = ["apple", "banana", "cherry"]

# Create a shallow copy
fruits_copy = fruits[:]

# Modify the copied list
fruits_copy[1] = "orange"

# Output the results
print("Original list:", fruits)    # Output: ['apple', 'banana', 'cherry']
print("Copied list:", fruits_copy) # Output: ['apple', 'orange', 'cherry']
  • In this example, modifying fruits_copy does not affect the original fruits list because the strings are immutable, and the copy is shallow.

Summary of Python Copy Methods for Arrays (Lists):

Method Description Shallow/Deep Example
Assignment (=) Creates a reference to the original list. None (same object) copied_list = original_list
copy() Method Creates a shallow copy of the list. Shallow copied_list = original_list.copy()
Slicing ([:]) Creates a shallow copy of the list. Shallow copied_list = original_list[:]
list() Function Creates a shallow copy of the list. Shallow copied_list = list(original_list)
deepcopy() from copy Creates a deep copy of the list. Deep copied_list = copy.deepcopy(original_list)

 

Conclusion

In Python, copying arrays (or lists) is a common task, especially when you want to modify a copy of a list without affecting the original.

In this tutorial, we covered:

  • Different methods of copying lists, including assignment, copy() method, slicing, list() function, and deepcopy.
  • The difference between shallow copies and deep copies, and when to use each.
  • Practical examples of copying simple lists and nested lists.

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