Iterating through two lists

Mark McEahern marklists at mceahern.com
Fri May 24 08:14:16 EDT 2002


[jb]
> I should like to achive this (x is a list of class instances)
>
>   for (a,b) in (x,y): a.f(b)

zip, as others have posted, does the trick.  Here's a solution using
generators:

#! /usr/bin/env python

from __future__ import generators

def walklists(m, n):
    i = 0
    while 1:
        if i >= len(m) or i >= len(n):
            break
        yield (m[i], n[i])
        i += 1

# Setup m and n.

g = walklists(m, n)

for a, b in g:
    print a.f(b)

-






More information about the Python-list mailing list