Xor tuple function
Question: I'm a beginner in python and I'm blocked on a series of instructions I have to
do. I need to make a function that takes into parameter two tuples of 3
integers. The function will perform a xor between the 2 first integers, then
the 2 second integers, and the 2 third integers. Finally, it will return these
results as a tuple.

Here's the function I used earlier in the code:

    
    
    def xor (a,b):
        return (bool (a) and not(bool(b))) or (not(bool (a))) and bool (b)
    

If it's not accurate or downright false, please let me know. Thanks!


Answer: In Python, the `^` infix operator represents xor for integers (you can see
this by looking at the documentation for `int.__xor__` but _be careful_ , the
`__xor__` behavior can be overloaded for other types and may not reflect
anything related to a usual logical xor operation).

So in this case, you can do it like:

    
    
    def xor(tup_a, tup_b):
       return tuple(a^b for a,b in zip(tup_a, tup_b))
    

For example:

    
    
    In [5]: xor((1,2,3), (3, 2, 1))
    Out[5]: (2, 0, 2)
    

This makes use of the `zip` function, which you should read about if not
familiar. One convention about this function: if `tup_a` and `tup_b` do not
have the same lengths, then the zipping process will only happen up to the
length of the shorter one, and the rest of the items from the longer one will
be discarded.

If you want to write some extra code to do something special to handle those
extra items, you'll have to modify this function definition to use
`itertools.izip_longest`.

For example, suppose that if `tup_a` is shorter than `tup_b` then you want to
use a dummy value of `0` in the places where `tup_a` isn't long enough to
match up with something from `tup_b` ...

    
    
    from itertools import izip_longest
    def xor(tup_a, tup_b, fill=0):
        return tuple(a^b for a,b in izip_longest(tup_a, tup_b, fillvalue=fill))
    

Then:

    
    
    In [11]: xor((1,2,3), (3, 2, 1))
    Out[11]: (2, 0, 2)
    
    In [12]: xor((1,2), (3, 2, 1))
    Out[12]: (2, 0, 1)
    

