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 ofrange(10)
- Fill the list with
- 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)] print(List1)
List2 = [j**2 for j in range(10)] print(List2)
List3 = [k for k in range(100) if k % 2 == 0] print(List3)
List4 = [l.lower() for l in 'ABCDEFG'] print(List4)
List5 = ['_' for m in 'Hello World!'] print(List5)
List6 = [n for n in 'The Quick Brown Fox' if n.upper() == n and n != ' '] print(List6)
List7 = [word[0] for word in 'my race should continue on to the island shore to help ease boring eye strain tonight'.split()] print(List7)
List8 = [[row[i] for row in [[1,2,3],[4,5,6],[7,8,9]]]for i in range(3)] print(List8)
Code It - your own list comprehension
- Use list comprehensions to create the following lists.
- [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0]
- A list of all consonants in the sentence 'The quick brown fox jumped over the lazy dog'
- A list of all square numbers formed by squaring the numbers from 1 to 1000.