Sequence traversal

M.-A. Lemburg mal at lemburg.com
Mon Sep 27 17:12:30 EDT 1999


Sven Havemann wrote:
> 
> Hi!
> ===
> 
> List traversal is elegant in python! - But what if I want to step
> through two sequences in parallel?
> 
> l1 = list("Names ")
> l2 = [4,2,1,5,3,9]
> 
> for i in l1:                    #   cool and
>   if i=='a': print "a found"    #   very elegant!
> 
> for i in range(len(l1)):        #   not so cool
>   if l1[i]=='a' and l2[i]==2: print "a and 2 found!"
> 
> 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). - Before I look through the python sources or make performance
> measures I just wanted to know whether there's a more elegant solution
> to this!!!

List indexing is O(1) since they are stored in C arrays. Insertion
and deletion are O(n).

Using mxTools you can write:

import NewBuiltins # provided by mxTools
parallel = tuples # looks even nicer ;-)

# And then:
for x,y in parallel(l1,l2):
	# do something with x,y

mxTools is available from my Python Pages (see link below).

-- 
Marc-Andre Lemburg
______________________________________________________________________
Y2000:                                                    98 days left
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/






More information about the Python-list mailing list