Sequence traversal

Mike Fletcher mcfletch at vrtelecom.com
Thu Sep 23 13:25:10 EDT 1999


Normally, for speed, you would spell parallel iteration:

for (u,v) in map( None, lista, listb ):
	if u == 'a' and v == 2:
		print "a and 2 found"

The "None" argument giving the default action for map, which is to "tangle"
the lists into tuples, padding the shorter with None's to get equal length.
Depending on the size of your lists, however, this may still be a serious
performance penalty versus integer indexing (you're creating len(l) new
objects and a list to hold pointers to them all (note that the range()
command does the same, but that xrange doesn't)).  I haven't profiled the
various versions to see which is most appropriate, and I'd guess it'll be
platform and task dependent.

Note: the experiments with list comprehensions might make this look more
like (forgive my mangling of the syntax, just skimmed those discussions):

result = [ (u,v) -> if u=='a' and v==2 -> for u in lista -> for v in listb ]
for u,v in result:
	print u,v

While other proposals have centred on the more obvious:

for i indexing lista:
	if lista[i] == 'a' and listb[i] == 2:
		print 'yada'

Of course, that doesn't provide any bounds checking, so you'll die if b is
shorter than a.

Hope this helps,
Mike


-----Original Message-----
From: python-list-request at cwi.nl [mailto:python-list-request at cwi.nl]On
Behalf Of Will Ware
Sent: September 23, 1999 12:07 PM
To: python-list at cwi.nl
Subject: Re: Sequence traversal


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