Swap Variables - Kotlin vs Python

Jun 9th, 2022

6 min read

kotlinpython

Swapping the values of two variables is a necessity that will be encountered at some point, whether it be for small values, in sorting alogrithms, or for large data types. The most common method to perform this swap is to introduce a third temporary variable.

Temporary Variable

1var a = "alpha"
2var b = "beta"
3
4val temp = a
5a = b
6b = temp
7
8println("New value of 'a' = $a")
9println("New value of 'b' = $b")
kt
New value of 'a' = beta
New value of 'b' = alpha

This is perfectly fine for the occasional small swap but the extra memory may prove inefficient for larger values or more frequent swaps. It's also mildly cumbersome to have to initialize a new variable, especially when you know that other languages provide alternatives.

Python supports parallel assignment, which allows variables to be more concisely swapped without the use of a temporary variable.

1a = "alpha"
2b = "beta"
3
4a, b = b, a
5
6print(f"New value of 'a' = {a}")
7print(f"New value of 'b' = {b}")
py
New value of 'a' = beta
New value of 'b' = alpha

Line 4: On the right-hand side of the assignment, tuple packing creates a new tuple of two objects. Then, on the left-hand side, sequence unpacking accesses the objects in the order assigned.

Broken down further, this tuple packing and sequence unpacking can be visualized:

1a = "alpha"
2b = "beta"
3
4c = b, a # optionally use (b, a)
5print(f"'c' is a {type(c)}")
6
7a, b = c
8print(a == c[0])
9print(b == c[1])
py
'c' is a <class 'tuple'>
True
True

Due to Python being a dynamically typed language, parallel assignment could even be used to swap variables of different types.

1x = 1
2y = 99
3z = "text"
4
5x, y, z = z, x, y
6
7print(f"'x' = {x} 'y' = {y} 'z' = {z}")
py
'x' = text 'y' = 1 'z' = 99

In Kotlin, multiple assignment is possible via destructuring declarations using any data structure or class that declares componentN() functions. Unfortunately, this only works to create multiple variables, not to reassign existing ones simultaneously.

1var a = "alpha"
2var b = "beta"
3
4// Incorrect - will not compile
5// (a, b) = b to a
6
7val (aNew, bNew) = b to a // Works!
8
9val c = b to a // Also works
10a = c.first
11b = c.second
12
13println("New value of 'a' = $a")
14println("New value of 'b' = $b")
kt
New value of 'a' = beta
New value of 'b' = alpha

Line 6: b to a is equivalent to Pair(b, a).

Line 8: A new Pair is initialized & its values accessed by the existing variables (lines 9 and 10) using functions equivalent to component1() and component2().

So what alternative is there to creating a temporary variable in Kotlin?

Scope Function

We can take advantage of Kotlin's scope function also (apply would work too).

1var a = "alpha"
2var b = "beta"
3
4a = b.also { b = a }
5
6println("New value of 'a' = $a")
7println("New value of 'b' = $b")
kt
New value of 'a' = beta
New value of 'b' = alpha

Calling this function on an object with a provided lambda expression forms a temporary scope that accesses the context object (b in this case) for reassignment, before returning the original value of that context object (to be assigned to a).

This is concise and convenient as it also allows chained functions to be called on the returned original value, even while any number of actions are performed inside the temporary scope:

1var a = "alpha"
2var b = "beta"
3
4a = b.also {
5 println("Reassigning 'b'")
6 b = if (a.length > 3) a.repeat(2) else a
7 println("Done")
8}.uppercase().take(3)
9
10println("New value of 'a' = $a")
11println("New value of 'b' = $b")
kt
Reassigning 'b'
Done
New value of 'a' = BET
New value of 'b' = alphaalpha

Still curious about what's happening to b behind the curtain and how it can be mutated in one scope but returned unmutated in another?

If you're using IntelliJ IDEA, you can access Tools > Kotlin > Show Kotlin Bytecode > Decompile with the relevant codeblock selected to get a deeper look.

XOR Swap Algorithm

Bitwise operator tricks are always fun to discover and I've come across a few while solving the Project Euler problems, so here's a quick one for the completion of this post.

The exclusive or (XOR) operator can be used to swap the values of two variables without using a temporary variable; however, the practicality of its use isn't necessarily advantageous. Also, xor can only be called on instances of the integer number classes Byte Short Int Long (and their unsigned counterparts) and Boolean.

1var a = 9
2var b = 10
3
4a = a xor b
5b = b xor a
6a = a xor b
7
8println("New value of 'a' = $a")
9println("New value of 'b' = $b")
kt
New value of 'a' = 10
New value of 'b' = 9

So how does it work?

Remember that, as a logical operation, XOR (\nleftrightarrow) takes two booleans and returns true if, and only if, the booleans are different. When applied to types with a binary representation, like Int, the XOR operator compares each bit and returns 1 when the bits differ or 0 when they are equal.

a=1001  (decimal 9)b=1010  (decimal 10)a=10011010=0011b=10100011=1001  (decimal 9)a=00111001=1010  (decimal 10)\begin{align*} a&=1001\;\text{(decimal 9)}\\ b&=1010\;\text{(decimal 10)}\\ a&=1001\nleftrightarrow1010=0011\\ b&=1010\nleftrightarrow0011=1001\;\text{(decimal 9)}\\ a&=0011\nleftrightarrow1001=1010\;\text{(decimal 10)} \end{align*}

If you're curious about other ways to incorporate bitwise tricks into your normal coding thought process, check out the following links:


Thanks for reading!🏝️🥨🐍

|© 2026 bog-walk