On 7/11/19 10:55 AM, Mats Wichmann wrote: > On 7/10/19 6:30 PM, Sarah Hembree wrote: >> How might I best make a linked list subscriptable? Below is skeleton code >> for a linked list (my >> actual is much more). I've done __iter__ and __next__ but I would like to >> be able to do start:stop:stride I just can't figure out how. Suggestions or >> just hints please? > As a learning exercise this can be interesting, but as to practical > applications, one would like to ask "why"? If index into the list is > important, then choose a regular list; the "interesting" part of a > linked list, which is "next node" is then available as index + 1. > To expand on the question, the primary use of something like a linked list is that you want cheap insertions/deletions (of O(1)) and in exchange for that indexing becomes O(n), verse an array based list which has O(1) indexing but O(N) insertions/deletions (since you need to compact the array). Both can be iterated in O(1).
You can add an index operator that takes O(N) time to a linked list. obj[n] will call obj.__getitem__ (and you will also want to implement __setitem__, __delitem__), and check if the argument is a slice to handle slices. -- Richard Damon _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor