How do you decode an unfamiliar comprehension in three steps — and what happens when the expression you build is itself a list?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Work out on paper what this expression evaluates to, then write the answer down. Do not run it.
[len(e) for e in ['py', 12, 'stack', '3.14', 9.0] if type(e) == str]
Ask the three questions in order — what is iterated over, what is the condition, what is the expression — and look closely at which elements sit inside quotes.
Assign the resulting list to traced_lengths as a plain list literal.
Any iterable as the source sequence
Record that lists, tuples, range(6), range(1,9,2) and range(len(L)) all drive a comprehension, and evaluate [e**2 for e in range(6)] and [e**2 for e in range(8) if e%2 == 0] to their element lists.
Elements that are themselves lists
Evaluate [[e, e**2] for e in range(4) if e%2 == 1] element by element to [[1, 1], [3, 9]], and record [0 for e in range(100)] as the hundred-zeros list.
The three-step method for decoding a comprehension
Apply the steps — values iterated, values surviving the condition, expression applied — to [len(e) for e in ['xy', 'abcd', 7, '4.0'] if type(e) == str] and reach [2, 4, 3].