Python Filtered list comprehension
Build a pick list containing only nonempty bins.
A simple example
Filtered list comprehension
- Start with 1, 2, 3
- Do this Remove values below 2
- Result 2, 3
Syntax
[n for n in counts if n != 0]
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyClear empty stock bins from the pick list
A stockroom prints only bins that contain items a picker can collect. Empty bins appear twice in today's count, and both should disappear while the remaining quantities keep their order.
counts = [4, 0, 2, 0]
available = [n for n in counts if n != 0]
print(", ".join(map(str, available)))
4, 2
The comprehension visits the bins in order and includes both positive quantities.
Count packs on the delivery slip
A loading desk receives four item counts in sequence. Only positive quantities go to the packing desk. Which entries survive, in their original order?
Review print quantities
A print room records four job quantities, including a cancelled job. Only positive quantities go to the packing desk. Which entries survive, in their original order?
What to watch for
Assign a filtered result back to a slice if existing references must observe an in-place change.