Intermediate·7 min·intermediate · lists
List Comprehensions
List Comprehensions
[expr for x in seq if cond] — read it left to right.
Why bother
- One line, clear intent, faster than
for+.append() - Works for dicts (
{k: v for ...}) and sets ({x for ...}) too
When NOT to
- If the expression is complex, write the loop. Readability > cleverness.
- If you don't need the list (just want side effects), use a regular loop.
Try it
- Build a list of
(word, len(word))for words longer than 4 letters. - Convert
[1, 2, None, 3, None, 4]into[1, 2, 3, 4].