bhylu.com

Advertisements

List Exercises

Select positive stock counts into a new list while keeping the original sequence unchanged.

Understand the idea

Write your own solution before opening the worked answer. Predict the output from the supplied values, then compare the actual result. Check both an ordinary case and the boundary described below; a passing example is more useful when you can explain why it passes.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

Your task

Select positive stock counts into a new list while keeping the original sequence unchanged.

Show the worked solution
Python

stock = [0, 4, 0, 7]
available = [count for count in stock if count > 0]
print(available)
print(stock)

Check the result

The result is [4, 7], and the source remains [0, 4, 0, 7].

Test one more case

Extend the transformation to reject negative counts rather than quietly filtering invalid data.