Day 9: Data Structures: Organizing Your Data

  • Lists: Ordered, mutable collections of items (e.g., [1, 2, "apple", 3.14])
  • Tuples: Ordered, immutable collections of items (e.g., (1, "apple", True))

  • Sets: Unordered collections of unique items (e.g., {1, 2, "apple"})

  • Dictionaries: Unordered collections of key-value pairs (e.g., {"name": "Alice", "age": 30})

Key Considerations:

  • Mutability:

    • Mutable (lists, dictionaries, sets): Can be modified after creation.

    • Immutable (tuples): Cannot be changed after creation.

  • Order:

    • Ordered (lists, tuples): Elements maintain their insertion order.

    • Unordered (sets, dictionaries): Order is not preserved.

  • Choice of Data Structure:

    • Lists: Versatile for general-purpose collections.

    • Tuples: Ideal for fixed data or as dictionary keys for immutability.

    • Sets: Efficient for checking membership, removing duplicates, and performing set operations (union, intersection, difference).

    • Dictionaries: Powerful for mapping unique keys to arbitrary values.

Code Examples:

Python

# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")  # Add an element
print(fruits)  # Output: ["apple", "banana", "cherry", "orange"]

# Tuple (immutable)
coordinates = (10, 20)
# coordinates[0] = 15 (would cause an error because tuples are immutable)

# Set (unordered, unique elements)
unique_numbers = {1, 2, 2, 3, 3}  # Duplicates are automatically removed
print(unique_numbers)  # Output: {1, 2, 3}

# Dictionary (unordered, key-value pairs)
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"])  # Output: Alice