Start free

A level · 4 exercises

Python comprehensions

A comprehension builds a list in one line: [x * x for x in range(5)]. Add if to keep only some: [x for x in nums if x > 0].

The same works for sets {…} and dictionaries {key: value for …}.

nums = [int(x) for x in input().split()]
print([x * x for x in nums if x % 2 == 0])

Watch for: Clear first, short second: when a comprehension needs two ifs and two fors, a loop reads better.

Exercises

  1. Pythagorean triplesFind all triples a < b < c up to n with a*a + b*b == c*c, using a listAdvanced
  2. Pascal's trianglePrint the first n rows of Pascal's triangle: each row starts and ends with 1, andAdvanced
  3. Divisors tableFor every number from 1 to n, print the number, a colon, and its divisors.Advanced
  4. Word lengthsBuild a dictionary {word: length} with a dictionary comprehension (each word once,Advanced
Start with “Pythagorean triples”