Updating quantity
- Python course
- Beginner
- Lesson 51/116
- 6 min
Manage cart with update_quantity and remove_item.
Updating quantity
In this lesson we'll learn to update the quantity of an item in the cart. Lists are accessed by index; cart[0] is the first item:
cart = ["Apple", "Bread"]
cart[0] = "Apple x2"
print(cart) # ['Apple x2', 'Bread']Indexes start at 0. cart[0] = ... replaces the first item. This is the basic way to update list items.
Index access
We access list items by index. Indexes start at 0: cart[0] is the first, cart[1] the second.
cart = ["Apple", "Bread", "Milk"]
print(cart[0]) # Apple
print(cart[2]) # MilkNegative indexes count from the end: cart[-1] is the last item. This is handy for end checks.
Practice Update an item and print
Assign cart = ["Apple", "Bread"]. Update the first item with cart[0] = "Apple x2". Print print(cart).
Starter code
# Update an itemSample solution
cart = ["Apple", "Bread"]
cart[0] = "Apple x2"
print(cart)Expected output
['Apple x2', 'Bread']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In cart = ["a", "b"], what is cart[0]?
- "b"
- "a" Correct answer
- 0
- Error
Explanation: Index 0 is the first item: 'a'.
2 Update the first item
cart = ["Apple", "Bread"]
cart[____] = "Apple x2"
cart = ["Apple", "Bread"]
cart[0] = "Apple x2"
Explanation: cart[0] updates the first item.
3 Match the index concepts
| Term | Meaning |
|---|---|
cart[0] |
First item |
cart[1] |
Second item |
cart[-1] |
Last item |
cart[i] = x |
Update an item |