Sequence traversal

Will Ware wware-nospam at world.std.com
Thu Sep 23 12:06:49 EDT 1999


Sven Havemann (s.havemann at tu-bs.de) wrote:
> List traversal is elegant in python! - But what if I want to step
> through two sequences in parallel?

Yes, you can do that. Use map to convert l1 and l2 into a single list
whose elements are two-tuples, a thing from l1 and a thing from l2.
Then we can elegantly step thru this list.

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

for (u,v) in map(lambda x,y:(x,y), l1, l2):
    if u=='a' and v==2: print "a and 2 found!"

I think the map() operation will fail if l1 and l2 are different
lengths, but that's an experiment you can try yourself.

Then you had a question about whether it's more efficient to step
thru a list using implied loops ("for" or "map") or using an
explicit index. I recently stumbled across "An Optimizing Anecdote"
that treats this topic in some depth, at:
http://www.python.org/doc/essays/list2str.html
-- 
 - - - - - - - - - - - - - - - - - - - - - - - -
Resistance is futile. Capacitance is efficacious.
Will Ware	email:    wware @ world.std.com




More information about the Python-list mailing list