Home >Backend Development >Python Tutorial >How Can I Create an Immutable Copy of a List in Python?

How Can I Create an Immutable Copy of a List in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 03:37:14770browse

How Can I Create an Immutable Copy of a List in Python?

Creating an Immutable List Copy

In Python, while assigning list references like new_list = my_list, modifications to new_list surprisingly affect my_list. This occurs because instead of creating a distinct new list, Python merely copies the reference to the actual list, resulting in both new_list and my_list pointing to the same list.

To address this and prevent unexpected changes, it's essential to create a true copy of the list using various methods.

Cloning a List

To obtain an immutable clone or a shallow copy of a list, consider the following options:

  • list.copy() Method (Python 3.3 ):
new_list = old_list.copy()
  • List Slicing:
new_list = old_list[:]
  • list() Constructor:
new_list = list(old_list)

Deep Copying a List

If you need to copy the elements of the list as well, employ deep copying:

import copy
new_list = copy.deepcopy(old_list)

Example

Consider the following code:

import copy

class Foo:
    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)

# edit orignal list and instance 
a.append('baz')
foo.val = 5

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

Result:

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)]

This demonstrates how modifications to the original list and its instances only affect the original list and not its copied versions (b, c, d, and f).

The above is the detailed content of How Can I Create an Immutable Copy of a List in Python?. 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