Are Python deques linked lists?

Duncan Booth duncan.booth at invalid.invalid
Mon Dec 10 13:28:19 EST 2007


Peter Otten <__peter__ at web.de> wrote:

> Neil Cerutti wrote:
> 
>> On 2007-12-10, Duncan Booth <duncan.booth at invalid.invalid> 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.

It isn't its own iterator. The iterator is a separate generator object.

> 
> Look at the test code again -- there is a second iteration after the
> deletions (the list comprehension). 
> 
> 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 ;)
> 
Only if you try to modify the list from both of them. Non-modifying 
iterations don't interfere. Changing the code to handle modifications from 
simultaneous iterations is fairly straightforward but probably tedious to 
cover all possible cases: probably the simplest thing is to catch such 
cases and throw an exception.

But my point wasn't to give a bullet-proof implementation of a linked list, 
just to demonstrate that there is no bar to having one which lets you use a 
for loop and delete elements.



More information about the Python-list mailing list