List

Tutorial for Python List: Building a Simple Inventory System

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

List

1. Getting Started

First, let’s create an empty list that will serve as our inventory.

Python
inventory = []

2. Add Item

We will create a function to add items to our inventory. Each item will be a string.

Python
def add_item(item):
    inventory.append(item)
    print(f"Added {item} to the inventory.")

Example:

Python
add_item("Apple")
add_item("Banana")

3. Remove Item

Next, let’s create a function to remove an item from the inventory.

Python
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:

Python
remove_item("Apple")

4. List All Items

We also need a function to view all items in our inventory.

Python
def list_items():
    print("Items in the inventory:")
    for item in inventory:
        print(item)

Example:

Python
list_items()

5. Check Item Availability

It would be useful to have a function that checks if an item is available in the inventory.

Python
def check_availability(item):
    if item in inventory:
        print(f"{item} is available.")
    else:
        print(f"{item} is not available.")

Example:

Python
check_availability("Apple")

Finally, let’s put all these functions into a single program to form our simple inventory system.

Python
# 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.