A household tracks items to buy before going to the store.
What You Need to Understand
A small shopping-list program can add products, avoid accidental duplicate entries, and display the current list. It combines list methods, conditionals and iteration.
When to Use It
A household tracks items to buy before going to the store.
Step-by-Step Python Example
shopping_list = []
for product in ["milk", "bread", "milk", "eggs"]:
if product not in shopping_list:
shopping_list.append(product)
for position, product in enumerate(shopping_list, start=1):
print(f"{position}. {product}")
How the Example Works
The duplicate milk is skipped, and the remaining three items are numbered for display.
Example Output
1. milk
2. bread
3. eggs
['bread']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
products = ["bread", "milk"]
to_remove = "milk"
if to_remove in products:
products.remove(to_remove)
print(products)
Important Behavior and Edge Cases
List membership checks are linear, which is fine for a short shopping list. Normalize capitalization if Milk and milk should be treated alike.
Try It Yourself
Add a command that removes an existing product safely.
Common Beginner Mistakes
- List membership checks are linear, which is fine for a short shopping list. Normalize capitalization if
Milkandmilkshould be treated alike. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- A small shopping-list program can add products, avoid accidental duplicate entries, and display the current list.
- The duplicate
milkis skipped, and the remaining three items are numbered for display. - List membership checks are linear, which is fine for a short shopping list.