Skip to content
Advertisement

Constant time list slicing

Is there a library or whatever class that extends or conforms to list APIs that allows slicing in constant time?

With a list in Python, lst[1:] will copy the sublist which takes O(n) time. I need some alternative that all operations on lists like max, min, len, set and get would have the expected behaviour, only slicing should be O(1) and use the underlying original list with manipulation on indexing and length.

Is there some shelf class to use for this or do I have to make my own?

Advertisement

Answer

Well i didn’t find any acceptable answer so i implemented what i needed myself… hope this can be useful to the community…

Here is the implementation of SliceList

Its important to note that it is possible to slice a SliceList any amount of times and it will still work on the original list rather then making copies. Note that its getting less and less efficient to iterate a SliceList as you add more levels of slicings (even the first level is much less efficient then using list directly) but if your use case includes little iterations and retrivals but much more slicing then it may pay off, espicially for long lists, to slice a SliceList over slicing a list.

This solution is better then list when you dont mind paying much more time when iterating and retrieving values to gain more time when slicing

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement