[Tutor] List iteration

alan.gauld@bt.com alan.gauld@bt.com
Sun, 13 May 2001 00:05:21 +0100


> I would like to do some list iteration, is there a way to do 
> something like
> this:

In general when doing things with lists its worth checking the 
so called functional programming features:

map, filter, reduce and list comprehension(in V2)

In this case amp will do what you want provided the 
lists are of equal length (you can get around that 
as I'll show later):

> list_a = ['a', 'b', 'c']
> list_b = ['d', 'e', 'f']

result = map(lambda x,y:x+y, list_a, list_b)

If you need error checking for different lengths(map will use 
None by default) write a fuunction first:

def add2(x,y):
   if x == None: x = 0
   if y == None: y = 0
   return x+y

result = map(add2, list_a, list_b)

My online tutor has a page on functional programming which 
describes these functions(except list comprehensions).

Alan G
http://www.crosswinds.net/~agauld