Google+ Pieces o' Eight: List comprehensions are cool!

Thursday 6 October 2011

List comprehensions are cool!

Lists - or arrays - are an essential part of programming. While their usage varies depending on the problem being solved, the typical method of constructing one is to create a loop and append each new item to an array or list, as the following pseudo-code shows:

myList = new List

for i = 0 to 9

    myList.append(i)

end for

While this is perfectly ok, Python - and indeed other languages - provide an alternate method of creating lists based on existing lists known as list comprehensions. Lets see how the above pseudo-code example could be implemented in a Python list comprehension:

[i for i in range(10)]

The first and most immediate benefit is that the list comprehension took only one line of code to implement. This cuts down on the amount of boiler-plate required to do something as common as creating a list and also has the effect of making the code easier to read.

What if we wanted to build a list containing only the even numbers in the range? Well this is catered for by including an if clause in the comprehension:

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

(Here I used the modulo division operator to only append the item (i) to the list if the remainder of the division i/2 is equal to 0)

List comprehensions aren't just for ranges of numbers:

[c for c in "abjkfghi" if c in "abcdef"]

In this example I'm scanning through a string and only appending the character to the list if it appears in the string "abcdef", and:

[d for d in os.listdir(r"C:\Photos") if d.startswith("Holiday")]

here I'm looking though the directories in my Photos directory and only appending those directories that start with the word Holiday.

As you can probably see from those few trivial examples, list comprehensions are pretty flexible and powerful and they save a considerable amount of time!

No comments:

Post a Comment