Data Structures Lists, Tuples, Sets, Dictionaries (CRUD operations)

Python Basics: Data Structures

Python Basics: Data Structures

Master lists, tuples, sets, and dictionaries to organize and manipulate data like a pro!

1. Lists: Ordered & Mutable

A list stores ordered, changeable items (like a shopping list).

CRUD Operations

Operation Code Example Result/Action
Create fruits = ["apple", "banana", "cherry"] Creates a list.
Read print(fruits[1]) Output: banana (index 1).
Update fruits[0] = "avocado" Replaces "apple" with "avocado".
Delete fruits.pop(2) or del fruits[2] Removes "cherry".

Useful Methods:

  • append("mango"): Add to end.
  • insert(1, "orange"): Insert at index.
  • remove("banana"): Delete by value.
  • sort(): Sort alphabetically.

Example:


groceries = ["milk", "eggs"]  
groceries.append("bread")      # Create  
print(groceries[0])            # Read: "milk"  
groceries[1] = "cheese"        # Update: Replace "eggs"  
groceries.remove("milk")       # Delete  
print(groceries)               # Output: ["cheese", "bread"]  

            

2. Tuples: Ordered & Immutable

A tuple stores ordered, unchangeable items (like coordinates).

CRUD Operations

Operation Code Example Notes
Create colors = ("red", "green", "blue") Use parentheses.
Read print(colors[-1]) Output: blue (last item).
Update ❌ Not allowed (immutable). Use a list if you need changes.
Delete ❌ Can’t delete items. Delete entire tuple: del colors.

Use Cases:

  • Store constants (e.g., days of the week).
  • Return multiple values from a function.

Example:


dimensions = (1920, 1080)  
print(f"Width: {dimensions[0]}")  # Output: Width: 1920  

            

3. Sets: Unordered & Unique

A set stores unordered, unique items (like a math set).

CRUD Operations

Operation Code Example Action
Create scores = {90, 85, 90} Duplicates auto-removed: {90, 85}.
Read ❌ No indexing (unordered). Loop to access: for s in scores.
Update scores.add(95) Add item.
Delete scores.remove(85) Remove item.

Useful Methods:

  • union(), intersection(): Combine sets.
  • discard(): Remove without errors.

Example:


student_ids = {101, 102, 103}  
student_ids.add(104)        # Create  
student_ids.remove(101)     # Delete  
print(102 in student_ids)   # Check existence: True  

            

4. Dictionaries: Key-Value Pairs

A dictionary stores data as key-value pairs (like a locker system).

CRUD Operations

Operation Code Example Action
Create student = {"name": "Alex", "age": 12} Use curly braces.
Read print(student["name"]) Output: Alex.
Update student["age"] = 13 Modify value.
Delete del student["age"] Remove key-value pair.

Useful Methods:

  • keys(): Get all keys.
  • values(): Get all values.
  • get("name"): Safely retrieve values.

Example:


book = {  
    "title": "Python for Kids",  
    "author": "Jason R. Briggs",  
    "year": 2012  
}  
book["pages"] = 344          # Create new key  
print(book["author"])        # Read: "Jason R. Briggs"  
book["year"] = 2023          # Update  
del book["pages"]            # Delete  

            

Real-World Project: To-Do List Manager


todos = []  

while True:  
    task = input("Add a task (or 'quit'): ")  
    if task == "quit":  
        break  
    todos.append({"task": task, "done": False})  

print("\nYour To-Do List:")  
for idx, item in enumerate(todos):  
    status = "✓" if item["done"] else "◻"  
    print(f"{idx + 1}. {status} {item['task']}")  

            

Common Mistakes

  • ❌ Using list[wrong_index] → IndexError.
  • ❌ Modifying tuples → TypeError.
  • ❌ Assuming set/dictionary order → Unordered!

Comparison Table

Feature List Tuple Set Dictionary
Ordered Yes Yes No No (Py3.7+: insertion order preserved)
Mutable Yes No Yes Yes (keys are immutable)
Duplicates Allowed Allowed No Keys: No, Values: Yes

Practice Quiz

Which data structure uses key-value pairs?

Answer: Dictionary.

What’s the output?


numbers = {1, 2, 2, 3}  
print(numbers)  

            

Answer: {1, 2, 3}.

Fix the error:


my_tuple = (10, 20)  
my_tuple[0] = 30  

            

Answer: Tuples are immutable. Use a list instead.

Fun Activity: Create a Word Counter


word = "mississippi"  
counter = {}  

for letter in word:  
    if letter in counter:  
        counter[letter] += 1  
    else:  
        counter[letter] = 1  

print(counter)  # Output: {'m': 1, 'i': 4, 's': 4, 'p': 2}  

            

What’s Next?

Learn functions to organize your code into reusable blocks!

Post a Comment

Previous Post Next Post