Python for Rubyists, Part III: List Comprehensions

If you’ve been following along with this series, you already have a pretty solid foundation for getting out there and doing some programming in Python.

But there’s one tool that’s completely essential for programming in Python that doesn’t really have a parallel in Ruby, and that’s list comprehensions.

A brief refresher on lists: They’re a data structure that functions very similarly to arrays in other languages. For super basic applications, you can initialize them the boring way, like so:

my_list = []print(my_list)

If you then run the program in the command line, you get:

But let’s say you want to create a list of the integers from 0–9, inclusive. You could do it the hard way, like this:

my_list = []for i in range(10):
my_list.append(i)
print(my_list)

This works just fine. If you run the program, you’ll get this:

But Python gives us a much faster way to do this. List comprehensions allow you to build that for loop into the list assignment right when you declare it, like so:

my_list = [i for i in range(10)]print(my_list)

If you run the program now, the output is the same as it was before, a list with the integers from 0–9. But the syntax was a lot more concise.

You can also add conditionals to your list comprehensions. For example, let’s say you only wanted the even integers from 0–9. You could write it the long way, like this:

my_list = []for i in range(10):
if i % 2 == 0:
my_list.append(i)
print(my_list)

Like before, this works. You get the even integers from 0–9.

But you can do it much faster with a list comprehension:

my_list = [i for i in range(10) if i % 2 == 0]print(my_list)

Once again, the output of the program will be the same as before.

As you can probably imagine, there are all kinds of ways to get creative with list comprehensions. This should be enough to get you started, but W3Schools has a great tutorial if you’re looking to learn more.

In the meantime, the true power of Python begins to reveal itself!

Software developer and science/tech writer. Python, Ruby on Rails, JavaScript, React/Redux, Java. Fascinated by the amazing stories behind today’s tech.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store