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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
