Practice: Shopping List

Practice: Shopping List

This exercise combines the section: appending, index assignment, removal, len, and in.

Exercise

The starter code creates shopping with four entries.

  1. Append "eggs".
  2. Replace "bread" with "rye bread" by assigning to its index.
  3. Remove "soap" by value.
  4. Create item_count — the number of entries, using len.
  5. Create needs_milk — a boolean, True when "milk" is in the list.
  6. Print shopping, item_count, and needs_milk.

The final list is ['milk', 'rye bread', 'apples', 'eggs'].

Run your code to see the output, then press Submit.

Hints

  • "bread" is at index 1.
  • Do the removal before counting, or the count is off by one.

Tests

import unittest


class TestShoppingList(unittest.TestCase):
    def test_final_list_is_correct(self):
        self.assertEqual(shopping, ["milk", "rye bread", "apples", "eggs"])

    def test_item_count_is_4(self):
        self.assertEqual(item_count, 4)

    def test_needs_milk_is_true(self):
        self.assertIs(needs_milk, True)
shopping = ["milk", "bread", "soap", "apples"]

shopping.append("eggs")
shopping[1] = "rye bread"
shopping.remove("soap")
item_count = len(shopping)
needs_milk = "milk" in shopping

print(shopping)
print(item_count)
print(needs_milk)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.