List Comprehensions

List Comprehensions are wonderful things.
What is a list comprehension? It’s a bit of syntactic sugar that helps you filter and/or alter a list to create a new list. It makes your code shorter, more intuitive, and in many cases, faster. This is another example of Python making life much easier for you. I initially learned to program in C, and even when I switched over to Python I kept doing some things the C way. It took me a while to get around to thinking about things in a more Pythonic way. I want to illustrate the difference– Let’s take a simple case of turning a string “komodo” into a list.

In Python, using a for loop:

testString = “komodo”
newList = []
for x in testString:
        newList.append(x)

>>print newList
[‘k’, ‘o’, ‘m’, ‘o’, ‘d’, ‘o’]

That’s simple enough, but a list comprehension can make it even more so!

In Python, using a list comprehension:

testString = “komodo”
newList = [x for x in testString]

>>print newList
[‘k’, ‘o’, ‘m’, ‘o’, ‘d’, ‘o’]

Down to 2 lines, nice.

Of course, more can be done with list comprehensions. You can apply changes to the items that get filtered, like shifting each of the letters in the test string: (I don’t know why you would want to, I’m just saying it’s possible…)

testString = “komodo”
shiftedList = [chr(ord(x) +2) for x in testString]

>>> print shiftedList
[‘m’, ‘q’, ‘o’, ‘q’, ‘f’, ‘q’]

Or dividing all items in a list of numbers 10:
items = [10, 20, 30, 40, 50]
decimated = [x/10 for x in items]

>>print decimated
[1, 2, 3, 4, 5]
That example was unconditional– now we’ll look at filtering based on a condition.
Say we have a list of numbers and we only want those divisible by 3.
testNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The long way:
threesList = []
for x in testNumbers:
if x%3 == 0:
        threesList.append(x)

>>> print threesList
[3, 6, 9]

With a list comprehension:
threesLC = [x for x in testNumbers if x%3==0]

>>> print threesLC
[3, 6, 9]

And of course you can combine those concepts to transform and filter all at once. Say you want to square all numbers divisible by 3:
threesSqLC = [x**2 for x in testNumbers if x%3==0]

>>> print threesSqLC
[9, 36, 81]

You can use list comprehensions on nested loops, but we can save that for later.
Also, note that the concept of list comprehensions also works on sets and dictionaries!

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *