Python List

Working with real-world data: Shopping list

One of the practical applications of Python lists is storing and managing real-world data. Let's see how you can use lists to create a shopping list:


1. Define your Shopping List:

Start by creating an empty list to hold your shopping list items.

shopping_list = []


2. Adding Items:

Use the append() method to add items to your shopping list as you remember them.

shopping_list.append("apples")
shopping_list.append("bread")
shopping_list.append("milk")

print(shopping_list)  # Output: ["apples", "bread", "milk"]


3. Removing Items (Optional):

If you realize you already have something or decide not to buy it, you can remove it from the list using remove() or pop().

  • remove("item_name"): This removes the first occurrence of the specified item.
  • shopping_list.pop(): This removes and returns the last item from the list. You can specify an index for pop() to remove from a specific position.

4. Modifying Items (Optional):

You can change an item in your list by using its index within square brackets and assigning a new value.

shopping_list[1] = "whole wheat bread"  # Replace "bread" with "whole wheat bread"
print(shopping_list)  # Output: ["apples", "whole wheat bread", "milk"]


5. Additional Considerations:

  • You can extend your list functionality by adding more features like allow users to specify quantities (e.g., "2 apples"), categorize items (e.g., "Produce", "Dairy") or mark items as bought as you shop.
  • Remember, lists can store various data types. You can use a list of lists to create a more structured shopping list with categories and quantities.

By using Python lists, you can create a dynamic and customizable shopping list program that helps you stay organized and efficient at the grocery store!

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you define an empty shopping list in Python?

shopping_list = list()
shopping_list = ()
shopping_list = []
shopping_list = {}
Check Answer

What will be the output after executing: shopping_list = []; shopping_list.append("apples"); print(shopping_list)?

[]
["apples"]
["bread"]
["apples", "bread"]
Check Answer

Which method removes the last item from a shopping list?

clear()
discard()
pop()
remove()
Check Answer

How do you modify the second item in the shopping list?

shopping_list[1] = "whole wheat bread"
shopping_list.append("whole wheat bread")
shopping_list.add("whole wheat bread")
shopping_list.update(1, "whole wheat bread")
Check Answer

Which feature can enhance a shopping list in Python?

Storing only strings
Categorizing items
Adding expiration dates
Allowing duplicate items
Check Answer