Comprehensions
A comprehension builds a collection from a loop in one expression:
- list:
[n * n for n in nums] - set:
{abs(n) for n in nums} - dict:
{w: len(w) for w in words}
Add if at the end to filter: [n for n in nums if n > 0]. To transform
every item in one of two ways, put if ... else at the front instead:
["+" if n > 0 else "-" for n in nums]. Mixing these up is a common syntax
error.
Several for parts read left to right, like nested loops written on one
line. [x for row in grid for x in row] flattens a grid.
Comprehensions are faster than an append loop and interviewers expect them.
But past two for parts, or with long conditions, a plain loop is easier to
read. Readable beats clever.
Run it, then build a dict that maps each number in nums to its square.