This Python List Comprehension lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A list comprehension builds a new list in one expression. Read it as the value to keep, the loop, then the test.
Use it for a short filter or a small change to each item. A normal for loop is clearer when the body has several steps.
Example 1: Start here
The test sits at the end. This list keeps 82, 90, and 74.
scores = [61, 82, 90, 74] # a list; the values stay in this order
passed = [score for score in scores if score >= 70] # a list; the values stay in this order
print(passed)
Example 2: Build squares
The expression before for is the new value. range supplies 1, 2, 3, and 4.
print([n * n for n in range(1, 5)]) # in is True when the value is found
Example 3: Keep some items
The if at the end keeps only the values that pass.
scores = [60, 82, 74, 91] # a list; the values stay in this order
print([score for score in scores if score >= 80]) # keep the items that pass the test
Example 4: Make labels
Each name is transformed and collected into a new list.
names = ["Asha", "Arun"] # a list; the values stay in this order
print([name.upper() for name in names]) # in is True when the value is found
