What is the efficiency of python's list slicing?
Question:
I am wondering what is the efficiency of slicing lists in python?
For Example:
myList = [1, 2, 3, 4, 5]
newList = myList[1:4]
I’m looking for big-O notation (e.g. O(n)
).
Answers:
It’s O(n)
for list
s, and most sequence types, as slicing for most types performs a shallow copy, it doesn’t make views of the original data.
For some types, like memoryview
, Python 3’s range
, or third-party types like numpy
arrays, slicing makes views, not copies, so the cost is O(1)
, since constructing the view has identical cost regardless of the size of the view. The downside is that this can keep huge allocations alive because a single view exists on a small part of the allocation; this flaw is why most built-in types use a copying strategy instead of a view strategy.
I am wondering what is the efficiency of slicing lists in python?
For Example:
myList = [1, 2, 3, 4, 5]
newList = myList[1:4]
I’m looking for big-O notation (e.g. O(n)
).
It’s O(n)
for list
s, and most sequence types, as slicing for most types performs a shallow copy, it doesn’t make views of the original data.
For some types, like memoryview
, Python 3’s range
, or third-party types like numpy
arrays, slicing makes views, not copies, so the cost is O(1)
, since constructing the view has identical cost regardless of the size of the view. The downside is that this can keep huge allocations alive because a single view exists on a small part of the allocation; this flaw is why most built-in types use a copying strategy instead of a view strategy.