Python dilemma!

Python has become one of the most popular languages in fields of data science, machine learning, computational physics and other streams of science owing to its lucid nature and brevity in syntax. It is also preferred by web developers and programmers as it can help us create a cleaner code in lesser time. It was wrong of me to assume that a cleaner, shorter and more readable code; often referred to as “pythonic” by python lovers, will be faster than a normal code written in a much more exacting syntax.
Although I might seem to be cherry-picking, a simple example that I chose is illustrated below. Here, I am using the timeit module to gauge the time consumed in swapping two integers stored in separate variables in three different ways.

  1. The pythonic way — a,b = b,a
  2. The standard way — using a temporary variable
  3. The XOR way — using the exclusive or bitwise operator
import timeit

def test1():
a = 9
b = 10
temp = 0
a,b = b,a

def test2():
a = 9
b = 10
temp = 0
temp = b
b = a
a = temp
def test3():
a = a^b
b = b^a
a = a^b
if __name__ == ‘__main__’:
import timeit
print(timeit.timeit(“test1()”, setup=”from __main__ import test1"))
print(timeit.timeit(“test2()”, setup=”from __main__ import test2"))
print(timeit.timeit(“test3()”, setup=”from __main__ import test3"))

I ran the above code multiple times (also passing the number of iterations as an argument to the timeit function) and was surprised to find this-


Now, I am wondering what might be the reason that a basic feature of the language that makes it so forthcoming to developers and laymen alike, can instead be less efficient than the standard way. How does memory play a role here? Or is it just contingent on the compiler?

timeit may not be the best way to gauge efficiency but that is not the point. In no way I am suggesting that python codes are slower.

I would like to underscore that a simple code or a subroutine which can be written by beginners can have implications on other modules of the framework! Chaos theory as developed by Lorenz, suggests that a infinitesimally small change in one part of the system can affect the remaining parts of the system and a completely unimaginable outcome can be witnessed! I would love to allude to such inefficient programs as parasites!

An example of a Chaotic system — A double pendulum

I will tinker with that code and try to find why that is happening! Let me know your thoughts on this. Keep hacking.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Image Credits (Double Pendulum):

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.