Handle Groups of Data the Right Way
Python gives us powerful built-in data structures to handle groups of items. Whether youβre storing a list of fruits, a set of unique tags, or a product catalog, Pythonβs collections have you covered.
π’ 1. Lists β Ordered & Mutable #
A list is an ordered collection of items that can be changed (mutable).
fruits = ['apple', 'banana', 'orange']
β Properties:
- Ordered (indexed)
- Allows duplicates
- Mutable (can add, remove, or change)
π§ Common Operations:
fruits.append('grape') # Add item
fruits.remove('banana') # Remove item
fruits[0] = 'mango' # Modify item
len(fruits) # Length of list
π§ 2. Tuples β Ordered & Immutable #
A tuple is like a list, but cannot be changed after creation.
coordinates = (10, 20)
β Properties:
- Ordered
- Allows duplicates
- Immutable (cannot modify elements)
π Useful for data that should not change, like coordinates or constants.
x, y = coordinates # Tuple unpacking
π§Ή 3. Sets β Unordered & Unique #
A set stores unique items only and is unordered.
unique_fruits = {'apple', 'banana', 'apple'}
print(unique_fruits) # {'banana', 'apple'}
β Properties:
- Unordered
- No duplicates
- Useful for filtering and comparison
π§ Common Operations:
unique_fruits.add('mango')
unique_fruits.remove('banana')
π Sets donβt support indexing like lists or tuples.
π 4. Dictionaries β Key-Value Pairs #
A dictionary stores data as key: value
pairs.
product = {
'name': 'Milk',
'price': 50,
'stock': 20
}
β Properties:
- Unordered (in older Python versions), ordered from Python 3.7+
- Fast lookup by key
- Mutable
π§ Common Operations:
product['price'] = 55
product['category'] = 'Dairy'
del product['stock']
π 5. Iterating Through Collections #
You can use for
loops to iterate over all collection types.
List: #
for fruit in fruits:
print(fruit)
Tuple: #
for coord in coordinates:
print(coord)
Set: #
for item in unique_fruits:
print(item)
Dictionary (keys, values, both): #
for key in product:
print(key, product[key])
# OR
for key, value in product.items():
print(key, "->", value)
π§ When to Use What Collection Type? #
Type | When to Use |
---|---|
List | Ordered, needs frequent update, duplicates allowed |
Tuple | Fixed data, like coordinates or settings |
Set | Need uniqueness, fast membership tests |
Dict | When you want key-based access (like product name β price) |
π Real-World Use Case: Inventory System for a Grocery Store #
Letβs simulate a simple inventory system that:
- Stores products with prices and stock
- Allows adding and removing products
- Prints available inventory
β Code Example #
# Dictionary to store products
inventory = {
'milk': {'price': 50, 'stock': 20},
'bread': {'price': 30, 'stock': 15},
'eggs': {'price': 10, 'stock': 100}
}
# Function to print inventory
def show_inventory():
print("\nπ Available Inventory:")
for item, info in inventory.items():
print(f"{item.title()} - Rs.{info['price']} | Stock: {info['stock']}")
# Function to add a product
def add_product(name, price, stock):
inventory[name.lower()] = {'price': price, 'stock': stock}
print(f"β
{name.title()} added to inventory.")
# Function to remove a product
def remove_product(name):
if name.lower() in inventory:
del inventory[name.lower()]
print(f"β {name.title()} removed.")
else:
print(f"β οΈ {name.title()} not found.")
# Run a sample
show_inventory()
add_product("Butter", 60, 10)
remove_product("eggs")
show_inventory()
π§Ύ Sample Output #
π Available Inventory:
Milk - Rs.50 | Stock: 20
Bread - Rs.30 | Stock: 15
Eggs - Rs.10 | Stock: 100
β
Butter added to inventory.
β Eggs removed.
π Available Inventory:
Milk - Rs.50 | Stock: 20
Bread - Rs.30 | Stock: 15
Butter - Rs.60 | Stock: 10
π§ Key Takeaways #
Concept | What You Learned |
---|---|
Lists | Ordered collections with mutable data |
Tuples | Ordered but immutable |
Sets | Unordered, no duplicates |
Dictionaries | Key-value pairs for structured data |
Iteration | for loops work with all collections |
Real-World Usage | Grocery inventory using nested dictionaries |
π Wrap Up #
Python collections are the backbone of data manipulation. Once you master them, you can build:
- Shopping carts π
- To-do lists π
- User databases π§βπΌ
- Product catalogs π¦
- And much more!
π Coming Next: #
File Handling in Python
Learn how to read and write files, manage data from.txt
or.csv
, and build something practical like a Customer Order Tracker.
Want me to write that chapter too? Or package this one as a PDF/series for your site or YouTube content? Let me know!