Friday, December 2, 2016

Python Swap Function

In the coming semester it is likely that I will T.A. a course in Python. Lately I've been researching the language and using it for my pet projects that never get finished, interviews, etc...

One thing I found interesting is writing a swap in function. For some sorting algorithms we often have to swap the values at two indices in an array, so this does come up fairly often. What I found especially interesting was that you could do this in one line using Python. Where in most programming languages you have to write something like...
var swap = function swap(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
view raw jsSwap.js hosted with ❤ by GitHub


In Python, this can be written as... 
def __swap(arr,i,j):
arr[i], arr[j] = arr[j], arr[i]
view raw pySwap.py hosted with ❤ by GitHub


This is because Python evaluates assignments right to left. When the right hand side gets evaluated, Python creates a tuple (val_i, val_j) then assigns the variables in the left their corresponding tuple values. 

Most experienced Python programmers already knew this, but I found it pretty cool. All credit for the knowledge goes to this stack overflow post.