An inventory list includes quantities, but a report needs only low-stock items.
What You Need to Understand
An explicit for loop with an if statement can filter a list into a new list. This is easy to read and debug when you are first learning iteration.
When to Use It
An inventory list includes quantities, but a report needs only low-stock items.
Step-by-Step Python Example
quantities = [5, 0, 13, 2, 0]
low_stock = []
for quantity in quantities:
if quantity < 3:
low_stock.append(quantity)
print(low_stock)
How the Example Works
The loop evaluates every quantity and retains those below three; the source list remains unchanged.
Example Output
[0, 2, 0]
['Daniel']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
names = ["Al", "Maya", "Daniel"]
print([name for name in names if len(name) >= 5])
Important Behavior and Edge Cases
Do not change the same list you are iterating over when removing unwanted items; build a result list instead.
Try It Yourself
Filter all names whose length is at least five characters.
Common Beginner Mistakes
- Do not change the same list you are iterating over when removing unwanted items; build a result list instead.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- An explicit
forloop with anifstatement can filter a list into a new list. - The loop evaluates every quantity and retains those below three; the source list remains unchanged.
- Do not change the same list you are iterating over when removing unwanted items; build a result list instead.