Three Python Surprises
A little levity for unsettled times
As I write this in mid-October, we’re approaching the 7-month mark since the initial lockdown of the Corona Virus and there’s less than a month away from the presidential election. Everything feels serious, heavy, and draining. But wait — here’s a little fun stuff I learned in Python this past week!
I didn’t play many video games as a child (except for the original hand-held Pacman game), so it wasn’t until 2015 that I first heard of the term “Easter Egg” (as a hidden message, not the colorful egg) from the Tesla Model X. Recently I came across my first Pythonic Easter Egg and that little surprise lightened the day. I simply typed “import this” into my Jupyter notebook and got:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!
As a numbers geek, my second favorite Pythonic Easter Egg is:
The second and third little surprises came about when I was comparing the code for finding a prime number in R and Python.
After writing my Python code, I checked on-line for other versions and solutions. Several people on Stackoverflow used a for/else loop and that was a new one for me. A for/else loop?!? According to my research, the else clause of the for loop is a lesser-known feature. This was surprise #2 and here’s how it was used:
After more searching in Stackoverflow, I came across a code snippet that was considered very Pythonic. Surprise #3 was the all() function:
This was the first time I had seen the all() function used. The all() function accepts an iterable object (such as a list or dictionary) as an argument. If all the elements in the passed iterable are true, then the all() function returns true or else it returns false. If the iterable is empty then this function returns true.
Admittedly, it took me some time to work through the Pythonic version. I’m pretty sure I could not have written that on my own, but it was definitely a fun challenge to work through the sparse 3-line function. And having a little fun these days is good therapy.