Trace a list comprehension over short labels
Type one expression at a time and check its delimiters. · 192 words
In an AI experiment, short labels often need cleaning before comparison. A list comprehension builds a new list from an iterable, such as a list. Its form is [expression for item in iterable if condition]. The expression says what to store. The optional condition decides which items are kept. For example, labels = ['cat', 'dog', 'cat', 'bird'] and clean = [label.upper() for label in labels if label != 'cat'] produce ['DOG', 'BIRD']. Trace from left to right: 'cat' fails the test, 'dog' passes and becomes 'DOG', the second 'cat' fails, and 'bird' becomes 'BIRD'. The original list is unchanged because the comprehension creates a separate list.
A different experiment can turn valid readings into training features. With readings = [3, 8, -2, 5], the expression value * 10 stores a scaled value, while value > 0 rejects zero and negative readings. The code scaled = [value * 10 for value in readings if value > 0] gives [30, 80, 50]. Output order follows input order, even though skipped items disappear. This makes comprehensions useful for quick feature pipelines, but experiments should still check edge cases such as empty inputs and unwanted values.
Check your recall
In [s.upper() for s in names if len(s) > 3], which strings are kept, and what happens to each one?
Check your answer
Only strings longer than three characters are kept. Each kept string is converted to uppercase. A four-character string passes, but a three-character string does not, because the condition requires a length greater than three.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.