Python Copy List
## Python: How to Copy a List
In Python, copying a list is a common operation. However, simply assigning one list variable to another (e.g., `list2 = list1`) does not create a new list. Instead, it creates a new reference to the same underlying list object in memory. If you modify the new list, the original list will also change.
To create an independent copy of a list, Python provides several efficient techniques. This tutorial covers the most common methods to copy a list, complete with code examples and a discussion on shallow vs. deep copying.
---
## Methods to Copy a List
Here are the primary ways to copy a list in Python:
1. **Slicing (`[:]`)** β The most Pythonic and efficient way to copy a shallow list.
2. **The `list()` Constructor** β A highly readable, built-in type constructor.
3. **The `extend()` Method** β Appends elements of the original list to a new, empty list.
4. **The `copy()` Method** β A built-in list method introduced in Python 3.
5. **The `copy` Module (Shallow vs. Deep Copy)** β Essential when dealing with nested lists.
---
## Code Examples
### Method 1: Using List Slicing (`[:]`)
Slicing is one of the fastest and most common ways to clone a list in Python. By omitting the start and stop indices, Python copies the entire list.
```python
def clone_list(li1):
# Using slice syntax to copy the list
li_copy = li1[:]
return li_copy
# Original list
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_list(li1)
print("Original List:", li1)
print("Copied List:", li2)
```
**Output:**
```text
Original List: [4, 8, 2, 10, 15, 18]
Copied List: [4, 8, 2, 10, 15, 18]
```
---
### Method 2: Using the `list()` Constructor
The `list()` constructor creates a new list object initialized with the elements of the passed iterable.
```python
def clone_list(li1):
# Using the list() constructor
li_copy = list(li1)
return li_copy
# Original list
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_list(li1)
print("Original List:", li1)
print("Copied List:", li2)
```
**Output:**
```text
Original List: [4, 8, 2, 10, 15, 18]
Copied List: [4, 8, 2, 10, 15, 18]
```
---
### Method 3: Using the `extend()` Method
You can initialize an empty list and use the `extend()` method to append all elements from the original list.
```python
def clone_list(li1):
li_copy = []
# Appending elements using extend()
li_copy.extend(li1)
return li_copy
# Original list
li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_list(li1)
print("Original List:", li1)
print("Copied List:", li2)
```
**Output:**
```text
Original List: [4, 8, 2, 10, 15, 18]
Copied List: [4, 8, 2, 10, 15, 18]
```
---
### Method 4: Using the Built-in `copy()` Method
Python 3 lists have a built-in `.copy()` method that returns a shallow copy of the list. This is highly readable and explicit.
```python
li1 = [4, 8, 2, 10, 15, 18]
# Using the built-in copy() method
li2 = li1.copy()
print("Original List:", li1)
print("Copied List:", li2)
```
**Output:**
```text
Original List: [4, 8, 2, 10, 15, 18]
Copied List: [4, 8, 2, 10, 15, 18]
```
---
## Important Considerations: Shallow Copy vs. Deep Copy
All the methods shown above (slicing, `list()`, `extend()`, and `.copy()`) perform a **shallow copy**.
* **Shallow Copy:** Creates a new list object, but inserts references to the objects found in the original. If your list contains mutable objects (like other nested lists), modifying a nested list in the copy will also modify the original list.
* **Deep Copy:** Creates a new list object and recursively copies all objects found in the original. Changes to nested structures in the copy will not affect the original.
### Example: The Limitation of Shallow Copying Nested Lists
```python
# A nested list
original = [[1, 2], [3, 4]]
shallow_copied = original.copy()
# Modify a nested element in the copied list
shallow_copied = 99
print("Original:", original)
print("Shallow Copied:", shallow_copied)
```
**Output:**
```text
Original: [[99, 2], [3, 4]]
Shallow Copied: [[99, 2], [3, 4]]
```
*Note: The original list was modified because both lists share references to the nested lists.*
### Solution: Using `copy.deepcopy()`
To completely clone a nested list, use the `copy` module's `deepcopy()` function:
```python
import copy
original = [[1, 2], [3, 4]]
# Perform a deep copy
deep_copied = copy.deepcopy(original)
# Modify a nested element in the deep copied list
deep_copied = 99
print("Original:", original)
print("Deep Copied:", deep_copied)
```
**Output:**
```text
Original: [[1, 2], [3, 4]]
Deep Copied: [[99, 2], [3, 4]]
```
---
## Summary of Best Practices
| Method | Syntax | Copy Type | Best Used For |
| :--- | :--- | :--- | :--- |
| **Slicing** | `new_list = old_list[:]` | Shallow | Quick, Pythonic copying of flat lists. |
| **`copy()` Method** | `new_list = old_list.copy()` | Shallow | Explicit, highly readable code in Python 3. |
| **`list()` Constructor** | `new_list = list(old_list)` | Shallow | Converting other iterables (like tuples) to a list copy. |
| **`deepcopy()`** | `new_list = copy.deepcopy(old_list)` | Deep | Complex, nested lists where inner elements must be independent. |
YouTip