[Tutor] Variable Swap
Kent Johnson
kent37 at tds.net
Mon Jan 29 13:51:14 CET 2007
Steve Nelson wrote:
> Hello,
>
> I understand the use of xor to do a variable swap without a temporary variable:
>
>>>> x=2
>>>> y=3
>>>> y=x^y
>>>> x=x^y
>>>> y=x^y
>>>> x
> 3
>>>> y
> 2
>
>
> However, why do I see this?
>
>>>> y=x^y
>>>> y
> 1
Because 2 ^ 3 == 1, right? Are you sure you understand what xor does? It
is a bitwise exclusive or:
http://en.wikipedia.org/wiki/Xor#Bitwise_operation
By the way in Python you can write
x, y = y, x
as a readable alternative.
Kent
More information about the Tutor
mailing list