In this tutorial, we’ll demonstrate a practical use-case for Python lists by developing a simple inventory system. The system will allow you to add, remove, and view items, as well as check their availability in stock.
Table of Contents
- 1. Getting Started
- 2. Add Item
- 3. Remove Item
- 4. List All Items
- 5. Check Item Availability
- 6. Putting It All Together : GitHubLink
1. Getting Started
First, let’s create an empty list that will serve as our inventory.
inventory = []
2. Add Item
We will create a function to add items to our inventory. Each item will be a string.
def add_item(item):
inventory.append(item)
print(f"Added {item} to the inventory.")
Example:
add_item("Apple")
add_item("Banana")
3. Remove Item
Next, let’s create a function to remove an item from the inventory.
def remove_item(item):
if item in inventory:
inventory.remove(item)
print(f"Removed {item} from the inventory.")
else:
print(f"{item} is not in the inventory.")
Example:
remove_item("Apple")
4. List All Items
We also need a function to view all items in our inventory.
def list_items():
print("Items in the inventory:")
for item in inventory:
print(item)
Example:
list_items()
5. Check Item Availability
It would be useful to have a function that checks if an item is available in the inventory.
def check_availability(item):
if item in inventory:
print(f"{item} is available.")
else:
print(f"{item} is not available.")
Example:
check_availability("Apple")
6. Putting It All Together : GitHubLink
Finally, let’s put all these functions into a single program to form our simple inventory system.
# Initialize inventory
inventory = []
# Add Item
def add_item(item):
inventory.append(item)
print(f"Added {item} to the inventory.")
# Remove Item
def remove_item(item):
if item in inventory:
inventory.remove(item)
print(f"Removed {item} from the inventory.")
else:
print(f"{item} is not in the inventory.")
# List All Items
def list_items():
print("Items in the inventory:")
for item in inventory:
print(item)
# Check Item Availability
def check_availability(item):
if item in inventory:
print(f"{item} is available.")
else:
print(f"{item} is not available.")
# Using the Functions
add_item("Apple")
add_item("Banana")
list_items()
check_availability("Apple")
remove_item("Apple")
list_items()
Output:
Added Apple to the inventory.
Added Banana to the inventory.
Items in the inventory:
Apple
Banana
Apple is available.
Removed Apple from the inventory.
Items in the inventory:
Banana
And that’s it! You’ve successfully built a simple inventory system using Python lists. This tutorial aimed to demonstrate how lists can be a powerful and flexible tool in Python, particularly for storing and manipulating collections of items. Feel free to extend this base code to add more functionalities, like updating item quantities or categorizing items.