HelloWorld
HelloWorld

Reputation: 388

Python slicing and replacing

I'm trying to understand python slicing better, and how it works in the context of mutating arrays. Is this in-place? Is it O(1) memory or less? What's happening throughout this line?

For an example, if nums is an array and f is an integer. Where nums = [1, 2, 3, 4, 5, 6, 7] and f = 3.

nums[:] = nums[-f:] + nums[:-f] 

Does nums[:] use memory? I know that nums[-f:] + nums[:-f] reassigns the value based on f but what does the addition do?

Upvotes: 1

Views: 119

Answers (1)

ggorlen
ggorlen

Reputation: 57289

This splits the list into two halves based on f. [-f:] extracts the last f elements of the list as a new list and [:-f] extracts the beginning of the list to len(nums) - f as a new list.

nums[:] uses memory for temporarily storing removed objects (recycle_on_stack/recycle) and copying the new ones into the list. [:] means we traverse the entire structure which means norig is the full length of the list and we have to incur

s = norig * sizeof(PyObject *);
memcpy(recycle, &item[ilow], s);

on the whole list. See the source code.

The slice assignment mutates nums in place, sort of like a splice operation.

+ in this context is list concatenation. The operation creates and returns a new list.

I'm counting at least 4 whole copies being made of nums in the above example (the two slices add up to one, one for the concatenation, and another two for the slice assignment).

Upvotes: 3

Related Questions