List Comprehension in Python

I stumbled across this nice tutorial on advanced design patterns in python today, and especially liked the following image that explains graphically what list comprehension is:

list1

List comprehension in python is extremely flexible and powerful. Let us practice some more with further neat examples of it:

Square all non-negative numbers smaller than 10

[x**2 for x in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Non-negative multiples of 5 smaller than 100

[x for x in range(100) if x%5 == 0]

[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Non-negative multiples of 3 but not multiples of 6 smaller than 50

[x for x in range(50) if x%3 == 0 and x%6 != 0]

[3, 9, 15, 21, 27, 33, 39, 45]

All consonants in a given sentence (without repetition)

import string
punct = string.punctuation + ' '
vowels = "aeiou"
phrase = "On second thought, let's not go to Camelot. It is a silly place."
set([c for c in phrase.lower() if c not in vowels and c not in punct])

{'c', 'd', 'g', 'h', 'l', 'm', 'n', 'p', 's', 't', 'y'}

First character of every word in a sentence

[w[0] for w in phrase.split()]

['O', 's', 't', 'l', 'n', 'g', 't', 'C', 'I', 'i', 'a', 's', 'p']

Substitute all vowels in a sentence by the character ‘0’

"".join([c if c not in vowels else '0' for c in phrase])

"On s0c0nd th00ght, l0t's n0t g0 t0 C0m0l0t. It 0s 0 s0lly pl0c0."

Pairs of elements drawn from different lists

words1 = ['Lancelot', 'Robin', 'Galahad']
words2 = ['Camelot', 'Assyria']
[(w1,w2) for w1 in words1 for w2 in words2]

[('Lancelot', 'Camelot'), ('Lancelot', 'Assyria'), ('Robin', 'Camelot'), ('Robin', 'Assyria'), ('Galahad', 'Camelot'), ('Galahad', 'Assyria')]

I will update this list as more interesting and useful examples come to mind. What’s your favorite use of list comprehension and how many lines of code did it save you?

Advertisements

3 comments

    • datasciencelab

      Indeed itertools rocks, and I love product, permutation, combination, etc. It is also more efficient than my example since it uses generators (just imagine if words1, words2 where *huge* lists, list comprehension wouldn’t be very good then).

      So yeah, hurra for itertools; my example was just to show that one can loop over two or more entities using list comprehension.

Post a comment

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s