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
Patricia ArquetteOriginal
2024-12-25 00:57:17405browse

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()
  • Slicing:
new_list = old_list[:]
  • list() Constructor:
new_list = list(old_list)
  • copy.copy() Function:
import copy
new_list = copy.copy(old_list)
  • copy.deepcopy() Function: (Copies nested elements recursively)
import copy
new_list = copy.deepcopy(old_list)

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}')

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

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!

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