Are Python deques linked lists?

Neil Cerutti horpner at yahoo.com
Mon Dec 10 13:40:01 EST 2007


On 2007-12-10, Neil Cerutti <horpner at yahoo.com> wrote:
> On 2007-12-10, Peter Otten <__peter__ at web.de> wrote:
>> Neil Cerutti wrote:
>>>> def test():
>>>>     ll = LinkedList([random.randint(1,1000) for i in range(10)])
>>>>
>>>>     for el in ll:
>>>>         if el.value%2==0:
>>>>             ll.delete(el)
>>>>
>>>>     print [el.value for el in ll]
>>>>
>>>>
>>>> if __name__=='__main__':
>>>>     test()
>>>>
>>>> Support for deleting elements other than the current one, and
>>>> insertBefore/insertAfter methods is left as an exercise.
>>> 
>>> Making an object its own iterator [works] for files, but not
>>> for a container. After the deletions, you can never iterate
>>> again.
>>
>> Look at the test code again -- there is a second iteration
>> after the deletions (the list comprehension). 
>
> Thanks for the correction. I didn't think that through.
>
>> However, you will get into trouble if you try to run two
>> simultaneous iterations over the same LinkedList, so there is
>> room for another exercise ;)
>
> I just remembered that iter(an_iterator) is itself, so nothing
> prevents you from saving a reference to it before iterating:
>
> iter = iter(a_linked_list)
> for it in iter:
>   if it.value % 2 == 0:
>     iter.delete()
>   
> It looks a little weird, but perhaps it's still better than a
> while loop.

Ugh! Assuming you don't shadow built-ins. ;-)

-- 
Neil Cerutti



More information about the Python-list mailing list