Home >Backend Development >Python Tutorial >How to Properly Clone Lists in Python and Avoid Unexpected Modifications?

How to Properly Clone Lists in Python and Avoid Unexpected Modifications?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 22:16:16135browse

How to Properly Clone Lists in Python and Avoid Unexpected Modifications?

Cloned Lists: Preserving Integrity in Python

In Python, assigning a new variable to an existing list creates a shallow copy, leaving you susceptible to unexpected list modifications. Let's shed light on why this behavior occurs and explore effective cloning methods to ensure list immutability.

Why assignment doesn't lead to cloning:

When you execute new_list = my_list, you assign a pointer to the same list object to new_list. Both variables refer to the original list, making any subsequent modifications visible in both new_list and my_list.

Copying the list effectively:

To create a genuine clone, you have several approaches:

1. Using list.copy():

This method, introduced in Python 3.3, creates a distinct copy of the list.

**2. Slicing the list with [:]:**

This syntax creates a new list with the same elements as the original.

3. Using the list constructor (list()):

This creates a new list from an existing iterable, such as another list.

4. Using copy.copy():

This built-in function provides a basic shallow copy, sufficient for most use cases.

5. Using copy.deepcopy():

This more comprehensive method creates a deep copy, where nested objects are also cloned.

Example:

Let's compare the results of these methods:

import copy

my_list = ['foo', 'bar']

new_list = my_list.copy()
sliced_list = my_list[:]
list_constructor_list = list(my_list)
shallow_copy_list = copy.copy(my_list)
deep_copy_list = copy.deepcopy(my_list)

my_list.append('baz')

print(f'Original list: {my_list}')
print(f'Copied list: {new_list}')
print(f'Sliced list: {sliced_list}')
print(f'List constructed from iterator: {list_constructor_list}')
print(f'Shallow copy: {shallow_copy_list}')
print(f'Deep copy: {deep_copy_list}')

Output:

Original list: ['foo', 'bar', 'baz']
Copied list: ['foo', 'bar']
Sliced list: ['foo', 'bar']
List constructed from iterator: ['foo', 'bar']
Shallow copy: ['foo', 'bar']
Deep copy: ['foo', 'bar']

As evident from the output, my_list is altered after appending 'baz', while the cloned lists remain unmodified.

The above is the detailed content of How to Properly Clone Lists in Python and Avoid Unexpected Modifications?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn