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.
Consider a list containing integer objects:
a = [1000 + 1, 1000 + 1, 1000 + 1]
Despite having identical values, each integer is a distinct object with a unique ID:
map(id, a) [140502922988976, 140502922988952, 140502922988928]
Slicing the list:
b = a[1:3]
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]
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)))
Despite the overhead, slicing lists is still a more efficient approach compared to creating completely new lists.
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])
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!