Bitpath

Lesson 2 · Unit 05

Comprehensions and sorting

Build, sort and sum up collections in one line

13 exercisesabout 3 min

What you practise

  • List, dictionary and set comprehensions, sorted with key and reverse, enumerate, zip, sum, min and max, any and all

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?

Python
nums = [1, 2, 3]
doubled = []
for n in nums:
    doubled.append(n * 2)

short = [n * 2 for n in nums]
print(short == doubled)

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.

Python
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().

Python
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.

One email when Bitpath is ready to try. Nothing else. Privacy