Skip to main content

Section 9.20 Advanced Topic: List Comprehensions

The remove_negative function from Section 9.17 creates a new list from a sequence of values based on some selection criteria (“keep only if non-negative”) using a for loop. Another way to do this type of processing in Python is to use a list comprehension. List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if  <condition>]
where the if clause is optional. For example,
The expression describes each element of the list that is being built. The for clause iterates through each item in a sequence. The items are filtered by the if clause when there is one. In the example above, the for statement lets item take on all the values in the list mylist. Each item is then squared before it is added to the list that is being built. The result is a list of squares of the values in mylist. (There is nothing magic about the name item; it is just a convenient and meaningful name.)
Here is a rewrite of remove_negative that filters a sequence of integers with a list comprehension.
In the list comprehension on line 5, the for loop looks at each number in a_list and puts number into the result if number >= 0.

Exercises Exercises

1.

    What is printed by the following statements?
    a_list = [4,2,8,6,5]
    b_list = [num * 2 for num in a_list if num % 2 == 1]
    print(b_list)
    
  • [4,2,8,6,5]
  • Items from a_list are doubled before being placed in b_list.
  • [8,4,16,12,10]
  • Not all the items in a_list are to be included in b_list. Look at the if clause.
  • 10
  • The result needs to be a list.
  • [10].
  • Yes, 5 is the only odd number in a_list. It is doubled before being placed in b_list.

2.

Rewrite Checkpoint 9.18.1 using a list comprehension. A word is “vowelicious” if it contains four or more vowels. (If you never heard this word before, it’s because I made it up just now for this book.) For example, “mountain” and “bookbinder” are vowelicious; “trailer” and “reading” are not.
Write a program that takes a list of words and creates a new list containing only the vowelicious words. Your program should have two pure functions:
  • count_vowels, which takes a string and returns the number of vowels it contains
  • keep_vowelicious, which takes a list of words and returns a new list containing only the words that have four or more vowels. This function must use a list comprehension.
Hint.
The list comprehension in the keep_vowelicious function should call the count_vowels function.
Solution.
def count_vowels(a_string):
    """ Return the number of vowels in the parameter string.
    
    Vowels are a, e, i, o, and u (upper and lower case).
    The letter y is not considered to be a vowel in this program.
    """
    total = 0
    for char in a_string:
        if char in 'aeiouAEIOU':
            total = total + 1
    return total
    
def keep_vowelicious(a_list):
    """Keep only words with four or more vowels.
    
    Given a list of words, return a new list that contains
    only words that have four or more vowels.
    """
    result = [item for item in a_list if count_vowels(item) >= 4]
    return result

words = ["beautiful", "locomotive", "friendly",
         "automation", "treadmill", "kangaroo"]
kept_words = keep_vowelicious(words)
print(f"The vowelicious words are {kept_words}")