Home > Backend Development > Python Tutorial > How to Create Truly Independent Copies of Python Lists?

How to Create Truly Independent Copies of Python Lists?

Patricia Arquette
Release: 2024-12-25 00:57:17
Original
356 people have browsed it

How to Create Truly Independent Copies of Python Lists?

Creating Unmodifiable Clones of Python Lists

When assigning new_list to my_list, it's not an actual separate list creation. Instead, it's just a reference pointing to the same list, causing any changes in new_list to be reflected in my_list.

Copying Lists Effectively

To avoid unexpected list modifications, several methods exist for list cloning:

  • list.copy() Method: (Python 3.3 ):
new_list = old_list.copy()
Copy after login
  • Slicing:
new_list = old_list[:]
Copy after login
  • list() Constructor:
new_list = list(old_list)
Copy after login
  • copy.copy() Function:
import copy
new_list = copy.copy(old_list)
Copy after login
  • copy.deepcopy() Function: (Copies nested elements recursively)
import copy
new_list = copy.deepcopy(old_list)
Copy after login

Example:

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

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')
foo.val = 5

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

The above is the detailed content of How to Create Truly Independent Copies of Python Lists?. 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