comparing tuples
Tim Chase
python.list at tim.thechases.com
Sun Aug 22 14:12:00 EDT 2010
On 08/22/10 12:50, Baba wrote:
> 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.
The ELSE clause can be used either with an IF (as you know) or
with a FOR loop, which is interpreted as "if this loop reached
the end naturally instead of exiting via a BREAK statement,
execute this block of code".
If you reach the end of t1 without having found a value (and then
issuing a "break"), then the current value of t2 (b) should be
appended to the result.
That said, unless order matters, I'd just use sets:
def tuples(t1, t2):
return list(set(t2)-set(t1))
which should have better performance characteristics for large
inputs.
-tkc
More information about the Python-list
mailing list