how fast is Python code - another detail

Josiah Carlson jcarlson at nospam.uci.edu
Sat Mar 6 00:01:33 CET 2004


Guillermo Fernandez Castellanos wrote:
> Skip Montanaro wrote:
> 
>>     >>> if sig not in d.keys():
>> vs.
>>     >> if sig not in d.iterkeys():
>> vs.
>>     if sig not in d:
>> The first must build the list of keys then search it sequentially.  The
>> second doesn't have to build the entire list, but still searches
>> sequentially.  The third effectively tries d[sig] and catches the 
>> KeyError
>> exception of sig is not a key in d.  The third is O(1) in the general 
>> case.
>> The others are O(len(d)).
> 
> Are all this also true for 'for' loops?
> 
> G.

For loops iterate.

for i in dict:
     pass

for i in dict.keys():
     pass

The dict.keys() generates the list of all keys (which takes time and 
memory), but the other doesn't.  What you do /inside/ the loop will 
determine which one is really faster.  EG:

for i in dict:
     break

for i in dict.keys():
     break

Obviously the first one will be faster, because i will just get a value, 
then the loop ends itself (if there are objects in the dictionary).  On 
the other hand, the second still has to build the list.

Testing for membership (if i in j) has different semantics than looping 
over an iterable (for i in j).

  - Josiah



More information about the Python-list mailing list