Introduction to Computer Science
CompSci 101 : Spring 2014

List Comprehensions

A Python list comprehension allows you to create a list from another sequence (i.e., something you can iterate over using a for loop). Note that a list comprehension is a list defined by a for-loop inside square brackets, and that the loop iterates over some sequence, creating a new list in the process. In the examples below, the output of each print statement is shown in italics.

print [ x*2 for x in range(0, 10) ]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

print [ s[0] for s in ['apple', 'termite', 'elephant'] ]
['a', 't', 'e']

print [ n % 2 == 0 for n in [2, 4, 6, 1, 3, 5, 8] ]
[True, True, True, False, False, False, True ]

print [ n for n in [2, 4, 6, 1, 3, 5, 8] if n % 2 == 0 ]
[2, 4, 6, 8]

Explain List Comprehensions

For the exercises below, first try using paper, pencil, discussion, and thinking (no computer) to solve them, before using the Python Interpreter to check your answers.

  1. print [ i*i for i in range(1, 10) if i % 2 == 0 ]
  2. print [ x**2 for x in range(1, 10, 2) ]
  3. print sum([ 1 for p in range(1, 9) ])
  4. print [ s[1] for s in ["big", "brown", "bare", "stem", "pea"] ]
  5. print [ 'po'*i for i in range(0, 5) ]
  6. print len([ x for x in "ostentatiously" if "aeiou".find(x) > -1 ])

Generate List Comprehensions

Write a list comprehension within the call to the function sum below that returns the only the odd integers in a list of integers named nums. So for the value [1, 3, 2, 4, 5] your list comprehension should create the list [1, 3, 5], so the entire expression evaluates to 9.

sum(                                                                                     )

Using a list comprehension and the list functions sum and len, write an expression that returns the average length of all the strings in a list of strings named strs. You will call two list functions: one with strs as an argument and one with a list comprehension using strs as an argument: combining in one expression sum(...) and len(...). For example, the average length of the strings in the list below is (3+3+4+5)/4 = 15/4 = 3.75

strs = ["cat", "dog", "bear", "tiger"]