The Essence of Pythonic

"Python is a very easy language".

I wish it were that simple. Python supports all the basic operations other languages do. If you know nearly any programming language, you can code in the same manner as you've always done as Python has an equivalent, and in that sense it's 'easy'. However if you do that you're not being pythonic.

Python has a slew of language features that can reduce the amount of code you write by orders of magnitude. Nearly every language feature was added to prevent writing common boilerplate code and complexity you've been writing your entire coding life. To learn a few of these things can save you signicant amounts of your time, reduce the complexity of a project, and actualy make you love programming again.

I coded in java for over 12 years, but I don't love it. When I discovered Python I fell in love with it. The reason is that the more I spent with Python the more I discovered kinds of code I didn't have to write anymore. After years of type based architectures, complex class hierarchies and these huge domains of code I found myself solving problems in a clearer manner with simpler code and significantly less of it.

Let's take the simple task of having a list of items and creating a dictionary where the key is the item and the value is the number of times it appeared in the list.

The syntax you learned in any language works here just fine in Python.

counts = {}
for i in items:
    if i in counts:
        c = counts[i]
        c += 1
        counts[i] = c
    else:
        counts[i] = 1

However python lets you reassign in a dictionary with one line which can reduce this a little.

counts = {}
for i in items:
    if i in counts:
        counts[i] += 1
    else:
        counts[i] = 1

Ok, so that's a little shorter, but you know what, that if statement doesn't seem like it's doing much except dealing with the special case of the item being absent. Thankfully Python lets me assign a default value when not present to kill that sort of statement.

counts = {}
for i in items:
    c = counts.get(i, 0)  # default to 0
    counts[i] = c + 1

Life looks a lot cleaner without that if statement. However Python doesn't stop there; it usually doesn't limit you. So you might wonder if it's possible to reduce the loop to one line. You can, and this is one of several ways.

counts = {}
[counts.update({i: counts.get(i, 0)+1}) for i in items]

Now that's excessive, and I'm not instructing you to do that, but I'm just making the point you can. All over Python there are funny little creative ways to reduce if you learn how to glue them together and develop the intuition to seek out the pythonic way.

Brad Willard4 Comments