[Tutor] smarter way of looping

Alan Gauld alan.gauld at freenet.co.uk
Thu Jan 26 15:18:25 CET 2006

> I often do a loop over arbitrary number of sequences. I do it like this:
>for elem1 in seq1:
>    for elem2 in seq2:
>        do whatever seq1,seq2
> this isn`t nice I think.

Actually its pretty common and not that ugly.

> myiterator=geniousfunction(seq1,seq2,seq3)
> and then myiterator.next()  and have it return the corresponding elemnts
> from all sequences

The problem is that there are so many different ways you can do that.
Python offers several options but none of them solve all the cases.

Look at the documentation for

List Comprehensions

> seq1 = ['a','b']
> seq2 = [1,2]
> a 1
> a 2
> b 1
> b 2

[a,b for a in seq1 for b in seq2]

> how do you loop over all the elements that can be returned by
> myiterator?

return the options as a list of tuples and then use the usual list iteration 

for elem in [a,b for a in seq1 for b in seq2]:
    # use elem here


Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list