Lesson 2 · Unit 05
Comprehensions and sorting
Build, sort and sum up collections in one line
What you practise
- List, dictionary and set comprehensions,
sortedwithkeyandreverse,enumerate,zip,sum,minandmax,anyandall
Try a question from this lesson
Pick one
Lines 2 to 4 build a list with a loop. Line 6 is new: read it as "n * 2, for each n in nums". What does this program show?
nums = [1, 2, 3]
doubled = []
for n in nums:
doubled.append(n * 2)
short = [n * 2 for n in nums]
print(short == doubled)Correct answer
True
Why
Line 6 does the whole job of lines 2 to 4: it makes a new list holding n * 2 for each n in nums. Both lists are [2, 4, 6], so they are equal. This one-line form is called a list comprehension.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
List comprehensions
A comprehension builds a new list from another collection, in one line inside square brackets.
First comes the value to put in the list, then the for part. An if at the end is optional: it keeps only the items that pass the test.
nums = [4, 7, 10]
plus_one = [n + 1 for n in nums]
print(plus_one) # [5, 8, 11]
big = [n for n in nums if n > 5]
print(big) # [7, 10]Concept
Sorting with a key
You know sorted and reverse=True from the gradebook. The new part is key=.
key= takes a function. It is called on every item, and the results decide the order. Pass the function's name without brackets: len, not len().
words = ["pear", "fig", "banana"]
print(sorted(words))
# ['banana', 'fig', 'pear']
print(sorted(words, key=len))
# ['fig', 'pear', 'banana']
print(sorted(words, reverse=True))
# ['pear', 'fig', 'banana']10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.