Skip to content

Data Structures ​

Master Python's essential data containers: lists, dictionaries, tuples, and sets for organizing and managing data effectively

πŸ“ Lists ​

Think of lists like shopping carts - you can add items, remove them, rearrange them, and access any item by its position.

Creating Lists ​

python
# Empty list (like an empty shopping cart)
empty_list = []
print(f"Empty list: {empty_list}")
print(f"Length: {len(empty_list)}")

# List with values
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]

print(f"Numbers: {numbers}")
print(f"Fruits: {fruits}")
print(f"Mixed types: {mixed}")

# Expected output:
# Empty list: []
# Length: 0
# Numbers: [1, 2, 3, 4, 5]
# Fruits: ['apple', 'banana', 'orange']
# Mixed types: [1, 'hello', 3.14, True]

List Operations ​

python
fruits = ["apple", "banana", "orange"]
print(f"Original fruits: {fruits}")

# Access elements by index (like numbered shelves)
print(f"First fruit: {fruits[0]}")     # Index 0 = first item
print(f"Last fruit: {fruits[-1]}")     # Index -1 = last item
print(f"Second fruit: {fruits[1]}")    # Index 1 = second item

# Modify elements
fruits[1] = "grape"
print(f"After changing second fruit: {fruits}")

# Add elements
fruits.append("kiwi")                   # Add to end
print(f"After adding kiwi: {fruits}")

fruits.insert(1, "mango")               # Insert at index 1
print(f"After inserting mango at position 1: {fruits}")

# Remove elements
fruits.remove("apple")                  # Remove by value
print(f"After removing apple: {fruits}")

popped = fruits.pop()                   # Remove and return last
print(f"Popped item: {popped}")
print(f"After popping: {fruits}")

del fruits[0]                           # Remove by index
print(f"After deleting first item: {fruits}")

# Expected output:
# Original fruits: ['apple', 'banana', 'orange']
# First fruit: apple
# Last fruit: orange
# Second fruit: banana
# After changing second fruit: ['apple', 'grape', 'orange']
# After adding kiwi: ['apple', 'grape', 'orange', 'kiwi']
# After inserting mango at position 1: ['apple', 'mango', 'grape', 'orange', 'kiwi']
# After removing apple: ['mango', 'grape', 'orange', 'kiwi']
# Popped item: kiwi
# After popping: ['mango', 'grape', 'orange']
# After deleting first item: ['grape', 'orange']

List Methods ​

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"Original numbers: {numbers}")

# Information methods
print(f"Length of list: {len(numbers)}")
print(f"Count of 1s: {numbers.count(1)}")
print(f"Index of 4: {numbers.index(4)}")
print(f"Minimum value: {min(numbers)}")
print(f"Maximum value: {max(numbers)}")
print(f"Sum of all numbers: {sum(numbers)}")

# Sorting and reversing
numbers_copy = numbers.copy()           # Create a copy
numbers_copy.sort()                     # Sort in place
print(f"Sorted (ascending): {numbers_copy}")

numbers_copy.sort(reverse=True)         # Sort descending
print(f"Sorted (descending): {numbers_copy}")

numbers.reverse()                       # Reverse in place
print(f"Reversed original: {numbers}")

# Expected output:
# Original numbers: [3, 1, 4, 1, 5, 9, 2, 6]
# Length of list: 8
# Count of 1s: 2
# Index of 4: 2
# Minimum value: 1
# Maximum value: 9
# Sum of all numbers: 31
# Sorted (ascending): [1, 1, 2, 3, 4, 5, 6, 9]
# Sorted (descending): [9, 6, 5, 4, 3, 2, 1, 1]
# Reversed original: [6, 2, 9, 5, 1, 4, 1, 3]

numbers.sort() # Sort in place print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]

numbers.reverse() # Reverse in place print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]


## πŸ“‘ **Tuples**

### **Creating Tuples**

```python
# Empty tuple
empty_tuple = ()

# Tuple with values
coordinates = (10, 20)
colors = ("red", "green", "blue")

# Single element tuple (note the comma)
single = (42,)

Tuple Operations ​

python
point = (10, 20, 30)

# Access elements
print(point[0])     # 10
print(point[-1])    # 30

# Tuple unpacking
x, y, z = point
print(x, y, z)      # 10 20 30

# Tuples are immutable
# point[0] = 15     # Error: cannot modify

πŸ—‚οΈ Sets ​

Creating Sets ​

python
# Empty set
empty_set = set()

# Set with values
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}

# From list (removes duplicates)
numbers = set([1, 2, 2, 3, 3, 4, 5])
print(numbers)      # {1, 2, 3, 4, 5}

Set Operations ​

python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Add/remove elements
set1.add(5)
set1.remove(1)      # Error if not found
set1.discard(10)    # No error if not found

# Set operations
print(set1 | set2)  # Union: {2, 3, 4, 5, 6}
print(set1 & set2)  # Intersection: {3, 4}
print(set1 - set2)  # Difference: {2}
print(set1 ^ set2)  # Symmetric difference: {2, 5, 6}

πŸ“š Dictionaries ​

Creating Dictionaries ​

python
# Empty dictionary
empty_dict = {}

# Dictionary with values
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Using dict() constructor
person2 = dict(name="Bob", age=25, city="Boston")

Dictionary Operations ​

python
person = {"name": "Alice", "age": 30, "city": "New York"}

# Access values
print(person["name"])           # Alice
print(person.get("age"))        # 30
print(person.get("height", 0))  # 0 (default value)

# Modify values
person["age"] = 31
person["height"] = 165

# Add new key-value pairs
person["email"] = "alice@example.com"

# Remove elements
del person["city"]
age = person.pop("age")

Dictionary Methods ​

python
person = {"name": "Alice", "age": 30, "city": "New York"}

# Get all keys, values, items
print(person.keys())    # dict_keys(['name', 'age', 'city'])
print(person.values())  # dict_values(['Alice', 30, 'New York'])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])

# Check if key exists
print("name" in person)     # True
print("height" in person)   # False

# Loop through dictionary
for key in person:
    print(f"{key}: {person[key]}")

for key, value in person.items():
    print(f"{key}: {value}")

πŸš€ Practice Examples ​

Example 1: Student Grade Tracker ​

python
# Using dictionary to store student grades
students = {
    "Alice": [85, 90, 78, 92],
    "Bob": [88, 76, 84, 91],
    "Charlie": [92, 95, 89, 87]
}

for student, grades in students.items():
    average = sum(grades) / len(grades)
    print(f"{student}: {average:.2f}")

Example 2: Word Counter ​

python
text = "hello world hello python world"
words = text.split()

word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)  # {'hello': 2, 'world': 2, 'python': 1}

Example 3: Shopping Cart ​

python
# Using list of dictionaries
shopping_cart = [
    {"name": "Apple", "price": 0.50, "quantity": 6},
    {"name": "Banana", "price": 0.30, "quantity": 8},
    {"name": "Orange", "price": 0.60, "quantity": 4}
]

total = 0
for item in shopping_cart:
    item_total = item["price"] * item["quantity"]
    total += item_total
    print(f"{item['name']}: ${item_total:.2f}")

print(f"Total: ${total:.2f}")

Example 4: Data Analysis ​

python
# Using various data structures
data = [
    {"name": "Alice", "department": "Engineering", "salary": 75000},
    {"name": "Bob", "department": "Marketing", "salary": 65000},
    {"name": "Charlie", "department": "Engineering", "salary": 80000},
    {"name": "Diana", "department": "Sales", "salary": 70000}
]

# Group by department
departments = {}
for person in data:
    dept = person["department"]
    if dept not in departments:
        departments[dept] = []
    departments[dept].append(person)

# Calculate average salary by department
for dept, employees in departments.items():
    avg_salary = sum(emp["salary"] for emp in employees) / len(employees)
    print(f"{dept}: ${avg_salary:,.2f}")

🎯 Key Takeaways ​

  • Lists: Ordered, mutable, allow duplicates
  • Tuples: Ordered, immutable, allow duplicates
  • Sets: Unordered, mutable, no duplicates
  • Dictionaries: Key-value pairs, mutable, unique keys
  • Choose the right data structure for your needs
  • Lists for ordered collections
  • Tuples for immutable data
  • Sets for unique elements
  • Dictionaries for key-value relationships

Continue to: File Handling β†’

Released under the MIT License.