[Tutor] Make a linked list subscriptable?

Cameron Simpson cs at cskk.id.au
Thu Jul 11 05:19:29 EDT 2019


On 10Jul2019 20:30, Sarah Hembree <sarah123ed at gmail.com> 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?

Well, you could write a method to find and return element `n`, counting 
from 0 (the root Node).

For start stop stride you could do the extremely simple approach: 
iterate over a range() of the start stop stride and call the 
get-element-n method. This will be very slow though (a complete scan for 
every element).

Instead, you could write a method accepting a start, stop and stride.  
Call the find-element-n method to get to start, lets call that `n`.  
While n < stop, step forward `stride` elements and also bump `n` by 
stride. That steps you along each element indicated by the 
start:stop:stride.

You'll notice that this only works for a positive stride.

For a negative stride you're probably better off handing it to range(), 
getting a list of values back from that as a list, and reversing the 
list (which then has ascending values). Collect the elements indicated 
by the list (because you can traverse the linkedlist forwards). Then 
reverse the collected elements and return them.

Now, you _could_ accumulate each element in a list and return that at 
the end. _Or_ you could make the function a generator and just yield 
each element as found.

To turn all this into a subscriptable list, define the __getitem__ 
method as a function accepting an index. If that index is an int, just 
return that element. If the index is a slice (start:stop:stride), call 
the more complicated function to return multiple elements.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list