Does Python's List Slicing Create Copies?

Linda Hamilton
Release: 2024-11-10 03:04:02
Original
567 people have browsed it

 Does Python's List Slicing Create Copies?

Slicing Lists in Python Without Copying: An Exploration

While slicing lists may appear to create new copies, the underlying truth is quite different. Python's slicing mechanism preserves the references to the list elements, rather than duplicating them. This behavior applies both to immutable and mutable values.

Testing Immutable and Mutable Values

Consider a list containing integer objects:

a = [1000 + 1, 1000 + 1, 1000 + 1]
Copy after login

Despite having identical values, each integer is a distinct object with a unique ID:

map(id, a)
[140502922988976, 140502922988952, 140502922988928]
Copy after login

Slicing the list:

b = a[1:3]
Copy after login

reveals that the IDs of the objects in the slice are identical to those in the original list. No copies have been made.

Similarly, mutable values like dictionaries behave the same way:

a = [{0: 'zero', 1: 'one'}, ['foo', 'bar']]
map(id, a)
[4380777000, 4380712040]

map(id, a[1:]
... )
[4380712040]
Copy after login

Minimal Memory Overhead

While object references are copied during slicing, their size remains constant (8 bytes on a 64-bit machine). Additionally, each list has an overhead of 72 bytes. This overhead increases with each slice created:

for i in range(len(a)):
    x = a[:i]
    print('len: {}'.format(len(x)))
    print('size: {}'.format(sys.getsizeof(x)))
Copy after login

Despite the overhead, slicing lists is still a more efficient approach compared to creating completely new lists.

Views and Numpy Arrays

Python does not offer a native way to create list views. However, numpy arrays provide a solution for saving memory by sharing memory between slices and the original array. Modifications made to the original array are reflected in the slices:

import numpy

a = numpy.arange(3)
b = a[1:3]

a[2] = 1001
b  # Output: array([   1, 1001])
Copy after login

However, using views requires careful consideration to avoid unintended modifications.

The above is the detailed content of Does Python's List Slicing Create Copies?. 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