Monday, May 6, 2019

The Code Bits: How to swap two variables in Python

In this post, we will explore different ways to swap variables in Python.

1. The Pythonic way: Tuple packing and unpacking syntax

The most standard way in which swapping is done in Python is using the tuple packing and unpacking syntax:

>>> a = "a"
>>> b = "b"
>>>
>>> a, b = b, a
>>>
>>> a
'b'
>>> b
'a'

You can think of the right-hand side as the creation of a tuple (the variables b and a are packed into a tuple). The left-hand side unpacks this tuple into the variables a and b, thereby resulting in swapping the two variables.

How does it work?

In order to see how it works, let us try to disassemble the line of code that does the swapping.

>>> import dis
>>> dis.dis("a, b = b, a")
  1           0 LOAD_NAME                0 (b)
              2 LOAD_NAME                1 (a)
              4 ROT_TWO
              6 STORE_NAME               1 (a)
              8 STORE_NAME               0 (b)
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE
  • The right-hand side of the expression is evaluated first, pushing the values of the two variables, ‘b’ and ‘a’ on to the stack, in that order.
  • Then, the key piece is the byte code instruction ROT_TWO, which, as per the Python documentation, swaps the two top-most stack items. Once this is done, the value of ‘b’ will be the TOS (top of stack) and the value of ‘a’ will be below it.
  • Finally, the values are stored back into the variables on the left-hand side. TOS (previous value of ‘b’) is first popped and stored in the first variable ‘a’. Then, the TOS(previous value of ‘a’) is popped again and stored in the second variable ‘b’.

2. Using a temporary variable

Generally, the most simplest way to think of swapping is by using a temporary variable.

>>> a = "a"
>>> b = "b"
>>>
>>> temp = a
>>> a = b
>>> b = temp
>>>
>>> a
'b'
>>> b
'a'

How does it work?

  • The value of variable ‘a’, is backed up in a temporary variable, ‘temp’.
  • Then the value of the variable ‘b‘ is assigned to the variable ‘a’.
  • Finally, the backed up value of ‘a’ in ‘temp’ is assigned to ‘b’.

3. Swap integers using XOR operation

Integers can be swapped using the bitwise XOR operation in three steps without using a temporary variable. Note that this does not work for other datatypes.

>>> a = 10
>>> b = -25
>>>
>>> a ^= b
>>> b ^= a
>>> a ^= b
>>>
>>> a
-25
>>> b
10

How does it work?

The binary XOR operation results in 1 if the two operands are not the same (one should be 1 and the other 0), and results in 0 if both the operands are the same.

>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0

So if we XOR two integers, all of the unlike bits result in 1 and the like bits result in 0. Hence, when we XOR two numbers(say, 5 and 7) and then XOR the result(2 in this case) with one of the two numbers(say, 7), then the final result would be the other number (5 in this case).

>>> bin(5)
'0b101'
>>> bin(7)
'0b111'
>>>
>>> bin(5^7), 5^7
('0b10', 2)
>>>
>>> bin(5^7^7), 5^7^7, 2^7
('0b101', 5, 5)

This is the technique employed in swapping two numbers.

>>> a = 10
>>> bin(a)
'0b1010'
>>> b = -25
>>> bin(b)
'-0b11001'
>>>
>>>
>>> a = a ^ b
>>> a, bin(a)
(-19, '-0b10011')
>>>
>>> b = a ^ b
>>> b, bin(b)
(10, '0b1010')
>>>
>>> a = a ^ b
>>> a, bin(a)
(-25, '-0b11001')

4. Swap numbers using arithmetic operations

We can also swap numbers using arithmetic operations as shown below. These should be self-explanatory.

Using addition and subtraction

>>> a = 100
>>> b = 30
>>>
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>>
>>> a
30
>>> b
100

Using multiplication and division

>>> a = 3.3
>>> b = 5.6
>>>
>>> a = a * b
>>> b = a / b
>>> a = a / b
>>>
>>> a
5.6
>>> b
3.3

Summary

Let us summarize the different swapping techniques we discussed:

  • Swap any variables using the tuple pack and unpack syntax
  • a, b = b, a
    
  • Swap any variables using a temporary variable
  • temp = a
    a = b
    b = temp
    
  • Swap integers using the bitwise XOR operator
  • a = a ^ b
    b = a ^ b
    a = a ^ b
    
  • Swap numbers using arithmetic operations
  • a = a + b
    b = a - b
    a = a - b
    
    a = a * b
    b = a / b
    a = a / b
    

The post How to swap two variables in Python appeared first on The Code Bits.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...