9  List Comprehensions

List comprehension is an elegant way to define and create lists based on existing lists. It offers a shorter syntax when you want to create a new list based on the values of an existing list.

9.1 Example

Iterating through a string Using for Loop

['N', 'I', 'B', 'A', 'F']

Iterating through a string Using List Comprehension

['N', 'I', 'B', 'A', 'F']

If you noticed, ‘NIBAF’ is a string, not a list. This is the power of list comprehension. It can identify when it receives a string or a tuple and work on it like a list.

9.2 Example

Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

['apple', 'banana', 'mango']

This can be done in one line of code With list comprehension:

['apple', 'banana', 'mango']

9.3 The Syntax

new_list = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

9.4 Key Points to Remember

  • List comprehension is an elegant way to define and create lists based on existing lists.

  • List comprehension is generally more compact and faster than normal functions and loops for creating list.

  • However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

  • Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.

9.5 Exercise

  1. Create the list [1,2,3,4,5] using list comprehension.

  2. Use a list comprehension that iterates over a_list, prints a list composed of each value in a_list multiplied by 10.

    a_list = list(range(1, 11))
  3. Use a list comprehension that iterates over a_list, prints a list composed of odd numbers from 1 to 9.

  4. Using a list comprehension which iterates over a_list and whose output expression accesses a value from a dictionary, print a list composed of the text form of each even number from 2 to 10, e.g., [ 'two', 'four', 'six', 'eight', 'ten' ].

    a_dictionary = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten'}

  5. Prompt the user for a number, which will be returned from input as a string data type. Strings can be iterated over like lists, such that the loop repeats for each character in the string. Using a list comprehension which iterates over the user-entered string and whose output expression accesses values from a_dictionary, print a list of the text form of each digit from the user-entered string, e.g., Enter a number: 195 return [ 'one', 'nine', 'five' ]

  6. Using the same user-entered number and list comprehension as above, also print the text form of the digits in a single string (using the string join function) with a dash between each text form of the digit, e.g.,

    one-nine-five
  7. Write a list comprehension that builds a list containing only the names with at least 4 characters. list9 = ['SBP', 'NIABF', 'HoK', 'PSPC', 'DPC']

  8. Write a list comprehension that builds a list containing only even numbers over 40.

    numbers = list (range (10,50,5))
  9. Add % in front and end of every single word in a given string str: “Fall is Awesome in Sakardu” only using list comprehensions. Desired Output

    ['%Fall%','%is%','%Awesome%','%in%','%Sakardu%']

  10. Use list comprehension to make a list of the first letter of each word in the following list:

    wordList = ["this", "is", "an", "apple"]

  11. A string is given:

    msg = "Long Live Pakistan!"

    Write a list comprehension that prints a list

    ['L', 'o', 'n', 'g', 'L', 'i', 'v', 'e', 'P', 'a', 'k', 'i', 's', 't', 'a', 'n']

    Do not print out the space or the !.