Python Key Skills - List Comprehension

1 List Comprehensions

Learn It

  • There is an easier way of creating lists in Python called List Comprehensions.
  • Using only one line of code you will create a list of data that meet certain criteria.

Code It

  • The easiest way of learning about list comprehensions is to write some.
numbersto10 = [number for number in range(10)]
  • We start by naming our list.
  • In the square brackets is the list comprehension.
  • This one says.
    • Fill the list with number
    • Where number is each element of range(10)
  • Let's have a look at another one.
foo = 'Hello World!'
bar = [character for character in foo]
  • Here we create a list containing all the characters that are in foo.

Try It

  • Type each line of the following code into a Python intepreter.
  • Try to understand how each list is created by examining the results
List1 = [i for i in range(20,10,-1)]
List2 = [j**2 for j in range(10)]
List3 = [k for k in range(100) if k % 2 == 0]
List4 = [l.lower() for l in 'ABCDEFG']
List5 = ['_' for m in 'Hello World!']
List6 = [n for n in 'The Quick Brown Fox' if n.upper() == n and n != ' ']
List7 = [word[0] for word in 'my race should continue on to the island 
shore to help ease boring eye strain tonight'.split()]
List8 = [[row[i] for row in [[1,2,3],[4,5,6],[7,8,9]]]for i in range(3)]

Code It - your own list comprehension

  • Use list comprehensions to create the following lists.
    1. [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0]
    2. A list of all consonants in the sentence 'The quick brown fox jumped over the lazy dog'
    3. A list of all square numbers formed by squaring the numbers from 1 to 1000.