Beautiful Code in Python

Before I ever looked at computer programming, words such “beautiful code” gave me only the vaguest sense of what people were talking about. What does that mean ? Is it merely efficient code ? Or does it refer to a sort-of Eureka type solution to a programming problem? Now that I’ve spent a couple of months looking at Python (BTW, I passed both my Python and PHP final exams this week – yeah !!!), I’m beginning to understand not only what beautiful code may be but also appreciate the clarity of Python.

When I was in high school, I took a year of BASIC programming. One of the few things I could remember from that was code like this.

10 FOR A = 1 TO 10



This always made complete sense. It’s so simple. You use a variable (A) to count loops till your variable reaches a certain value (10) and ends. The next level for me was stuff like this:

10 FOR A = 1 TO 10



In this example, you use the variable A for more than just counting loops. It’s also part of the output. Both methods are clean and simple solutions and give the beginner a sense of how to think like a programmer.

Yesterday, I came across a piece of code in O’Reilly’s “Python Cookbook” using List Comprehensions.

thenewlist = [ x + 23 for x in the oldlist if x > 5 ]

Even if you don’t know Python and don’t know what exactly a list is, it should be immediately clear what’s going on here. For me, it was a Eureka type moment realizing how simple and powerful Python is, if you can pack a loop, a condition, and an expression (?) into one line of code. I got a real kick out of this.


1 Comment

Filed under Uncategorized

One response to “Beautiful Code in Python

  1. (No space between ‘the’ and ‘oldlist’ 🙂

    – Paddy.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s