[Tutor] Performance list vs. deque for [-1]

Dave Angel davea at ieee.org
Thu Aug 12 12:10:36 CEST 2010


Knacktus wrote:
> Hi everyone,
>
> I'm wondering what's the fastet datatype in python to lookup the last 
> element in an ordered collection. I know about lists, of course, and 
> read about deques. As I understand deques have better performance for 
> popping and adding elements, but I didn't understand what's the 
> behavior for look-up's without any changes to the collection.
>
> I will not pop() out of my ordered collection, and only recently 
> append. Also, the collections will be small (about 10-20 elements), 
> but I will have huge amount (50000-100000) of those collections which 
> need to be processed for certain tasks in my application.
>
> Thanks in advance and cheers,
>
> Jan
>
Referencing the last element of a list by   items[-1] is very fast, and 
switching to a deque will not be any quicker, and probably a lot 
slower.  Indeed looking up any element if you know the index# is fast.  
It's only when you need to look up an item by its value that a deque 
gets to be quicker, and even there, I doubt if it'd help much for a list 
of only 10 items.

In case you ever do need to do pop(), realize that a pop(-1)  (which is 
the default you get if you just say pop() ), is very quick.

It's dangerous to make assertions like this without actually timing it, 
but I'd be surprised if a deque could beat a list on any of the above 
operations.

DaveA



More information about the Tutor mailing list