Sequence traversal

François Pinard pinard at iro.umontreal.ca
Thu Sep 23 12:50:17 EDT 1999


Sven Havemann <s.havemann at tu-bs.de> writes:

> List traversal is elegant in python! - But what if I want to step
> through two sequences in parallel?

Tee hee!  A question I know how to answer! :-) :-)

> I assume that indexing in a list l is not too efficient (O(log len(l))?),
> while stepping through l using 'for i in l' will certainly be O(1).

Indexing is efficient.  A list, despite its name, is allocated in a memory
array, so any item is accessed in constant time.  When the list grows,
the array might sometimes be reallocated -- some extra-space is included
at the end to foresee possible further grows.  A tuple is also allocated
as a memory array, but with no extra-space, because a tuple cannot grow.

> l1 = list("Names ")
> l2 = [4,2,1,5,3,9]

You might like to replace:

> for i in range(len(l1)):        #   not so cool
>   if l1[i]=='a' and l2[i]==2: print "a and 2 found!"

with:

   if ('a', 2) in map(None, l1, l2):
        print "a and 2 found!"

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list