Friday, September 6, 2013

List Comprehensions in Python

Python logo
Why hello there fellow netizens!  It's good to finally have been forced to start a blog because I certainly have a lot to share with the world.  This post will serve to be a short expose on a wonderful feature of the Python programming language (named after the t.v. show "Monty Python's Flying Circus") called List Comprehensions.  It's essentially a severely under-appreciated extension of Python's famous lists.  Before we jump in to the rest of the post, I suggest you familiarize yourself with Python lists using my demo on repl.it or the official Python docs if you don't already know how they work or need a refresher.


Ok, now let's start comprehending some lists! Say we have a list, x_list, that contains [1, 2, 3] and we want y_list to contain the value of each element of x_list squared.  That is to say, we want y list to contain [1, 4, 9].  Python makes this a very easy task indeed.

We could do it the schmuck way with a for loop:
x_list = [1, 2, 3]
y_list = []
for n in x_list:
    y_list.append(n * n)
print y_list

But, of course, Python supplies us mortals with List Comprehensions (a delightfully abbreviated syntax):
x_list = [1, 2, 3]
y_list = [n * n for n in x_list]
print y_list

Both versions print [1, 4, 9], but the List Comprehensions version is indisputably more elegant.  One thing I fail to understand is why the developers decided to make "Comprehensions" plural, but such is life.

1 comment:

  1. Wow thanks Max, that was a really helpful tutorial about list comprehensions.

    ReplyDelete