Collections

2 min read

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? #

TypeWhen to Use
ListOrdered, needs frequent update, duplicates allowed
TupleFixed data, like coordinates or settings
SetNeed uniqueness, fast membership tests
DictWhen 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 #

ConceptWhat You Learned
ListsOrdered collections with mutable data
TuplesOrdered but immutable
SetsUnordered, no duplicates
DictionariesKey-value pairs for structured data
Iterationfor loops work with all collections
Real-World UsageGrocery 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!

Updated on June 9, 2025