comparing tuples

Baba raoulbia at gmail.com
Sun Aug 22 13:50:47 EDT 2010


level: beginners

I was trying to write simple code that compares 2 tuples and returns
any element in the second tuple that is not in the first tuple.

def tuples(t1, t2):
    result = []
    for b in t2:
        for a in t1:
            if b == a:
                break
        else:
            result=result+[b,]
    return result

print tuples([0,5,6], [0,5,6,3,7])


the code works but i was surprised by the following: my understanding
was that an ELSE clause is part of an IF statement. Therefore it comes
at the same indentation as the IF statement.

However the above example only works if the ELSE clause is positioned
under the second FOR loop. As if it was an ELSE clause without an IF
statement....!?

Why/How does this work?

tnx
Baba




More information about the Python-list mailing list