Home > Backend Development > Python Tutorial > How Can I Create a True Copy of a Python List to Avoid Unintentional Modifications?

How Can I Create a True Copy of a Python List to Avoid Unintentional Modifications?

Linda Hamilton
Release: 2024-12-21 02:27:09
Original
711 people have browsed it

How Can I Create a True Copy of a Python List to Avoid Unintentional Modifications?

Cloning Lists for Unaltered Assignment: A Comprehensive Guide

In Python, assigning a list to a new variable using new_list = my_list isn't a genuine copy. Instead, a reference to the original list is created. Consequently, modifications to the new list also alter the original list.

To prevent these unexpected changes, it's essential to clone or copy the list. Here are several approaches:

  • Built-in list.copy() Method: (Python 3.3 and later)
new_list = old_list.copy()
Copy after login
  • Slicing:
new_list = old_list[:]
Copy after login
  • Built-in list() Constructor:
new_list = list(old_list)
Copy after login
  • Generic copy.copy():
import copy
new_list = copy.copy(old_list)
Copy after login
  • Generic copy.deepcopy(): (Copies nested elements)
import copy
new_list = copy.deepcopy(old_list)
Copy after login

Consider a sample with a nested list and an instance:

class Foo(object):
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return f'Foo({self.val!r})'

foo = Foo(1)

a = ['foo', foo]
b = a.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)

a.append('baz')  # Modify original list
foo.val = 5  # Modify nested instance

print(f'original: {a}\nlist.copy(): {b}\nslice: {c}\nlist(): {d}\ncopy: {e}\ndeepcopy: {f}')
Copy after login

Output:

original: ['foo', Foo(5), 'baz']
list.copy(): ['foo', Foo(5)]
slice: ['foo', Foo(5)]
list(): ['foo', Foo(5)]
copy: ['foo', Foo(5)]
deepcopy: ['foo', Foo(1)]
Copy after login

As you can see, while the original list and nested instance changed, only the deepcopy (f) has copied them accurately, preserving previous values.

The above is the detailed content of How Can I Create a True Copy of a Python List to Avoid Unintentional Modifications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template