python_learning learning week_1 Week1_Day2_Data_Structures-2.md
29 kB · 716 lines
Markdown
at main

Week 1 - Day 2: Data Structures — Lists, Tuples, Dictionaries, Sets #

learning/week_1/Week1_Day2_Data_Structures.md


1. Introduction: Why Are Data Structures Important? #

Data structures are concepts that determine how data is organized in memory, how it is stored, and how it is accessed. Choosing the right data structure directly affects a program's performance, readability, and scalability.

An analogy: how you arrange books on shelves in a library determines how quickly books can be found. Similarly, how you structure data in a program determines how quickly it can be accessed.

Python's built-in data structures are divided into four main categories:

Structure Ordered? Mutable? Allows Duplicates? Syntax
List ✅ Yes ✅ Yes ✅ Yes [1, 2, 3]
Tuple ✅ Yes ❌ No ✅ Yes (1, 2, 3)
Dictionary ✅ Yes (3.7+) ✅ Yes Key: ❌, Value: ✅ {"a": 1}
Set ❌ No ✅ Yes ❌ No {1, 2, 3}

[!tip] Best Practice — Think with Big-O When choosing a data structure, consider the time complexity of the main operations. For example, searching by element: O(n) in a list, O(1) in a set, O(1) with a key in a dict. In large datasets, this difference can determine the gap between seconds and milliseconds.


2. Lists #

2.1 What is a List? #

A list is Python's most widely used, ordered, mutable, and heterogeneous (capable of storing elements of different types) data structure. It is internally implemented as a dynamic array — this means elements are stored contiguously in memory and the array is automatically expanded when needed.

The mutability of a list is its key distinguishing feature from a tuple: after creation, elements can be added, removed, and modified.

2.2 Creating a List #

# Two ways to create an empty list
empty_list_1 = []          # Literal syntax — faster and more Pythonic
empty_list_2 = list()      # Constructor — more suitable for converting other iterables to a list

# Creating a list with elements
epochs = [10, 20, 50, 100, 200]              # Homogeneous list (all elements are int)
mixed = [42, "GPT", 3.14, True, None]        # Heterogeneous list (different types)
nested = [[1, 2], [3, 4], [5, 6]]            # Nested list (like a 2D array/matrix)

# Creating a list from other iterables using list() constructor
from_string = list("Python")          # ['P', 'y', 't', 'h', 'o', 'n']
from_range = list(range(0, 10, 2))    # [0, 2, 4, 6, 8]
from_tuple = list((1, 2, 3))          # [1, 2, 3]

2.3 Indexing & Slicing #

In Python, indices start from 0. Negative indices count backwards from the end.

layers = ["Input", "Conv2D", "BatchNorm", "ReLU", "Dense", "Softmax"]
#           0        1          2          3        4        5       (positive)
#          -6       -5         -4         -3       -2       -1       (negative)

# Accessing a single element (indexing)
print(layers[0])       # "Input" — first element
print(layers[-1])      # "Softmax" — last element
print(layers[3])       # "ReLU" — element at index 3

# Slicing — [start:stop:step]
# start is inclusive, stop is exclusive
print(layers[1:4])     # ['Conv2D', 'BatchNorm', 'ReLU'] — indices 1, 2, 3
print(layers[:3])      # ['Input', 'Conv2D', 'BatchNorm'] — from start up to 3
print(layers[3:])      # ['ReLU', 'Dense', 'Softmax'] — from 3 to the end
print(layers[::2])     # ['Input', 'BatchNorm', 'Dense'] — every second element
print(layers[::-1])    # ['Softmax', 'Dense', 'ReLU', 'BatchNorm', 'Conv2D', 'Input'] — reversed

# Making changes with slicing (because list is mutable)
layers[1:3] = ["Conv1D", "LayerNorm"]  # Replaces indices 1 and 2
print(layers)  # ['Input', 'Conv1D', 'LayerNorm', 'ReLU', 'Dense', 'Softmax']

2.4 List Methods #

Key methods that enable mutation and querying of a list:

Adding Elements #

# Starting list
pipeline = ["data_collection"]

# append() — Adds a single element to the end. O(1) amortized.
pipeline.append("preprocessing")
print(pipeline)  # ['data_collection', 'preprocessing']

# insert(index, element) — Inserts an element at a given index. O(n).
# All subsequent elements are shifted one position to the right.
pipeline.insert(1, "data_validation")
print(pipeline)  # ['data_collection', 'data_validation', 'preprocessing']

# extend() — Appends elements from another iterable to the end. O(k), k = number added.
pipeline.extend(["training", "evaluation", "deployment"])
print(pipeline)
# ['data_collection', 'data_validation', 'preprocessing', 'training', 'evaluation', 'deployment']

# '+' operator — Concatenates two lists to create a new list. O(n+m).
# Original lists are not changed.
extra_steps = pipeline + ["monitoring"]
print(extra_steps)  # [..., 'deployment', 'monitoring']
print(pipeline)     # Original unchanged

[!tip] Best Practice — append() vs + vs extend()

  • To add a single element: append() — O(1)
  • To add multiple elements: extend() — O(k)
  • The + operator creates a new list every time — using list = list + [item] inside a loop leads to O(n²) complexity. Use append() instead.

Removing Elements #

frameworks = ["TensorFlow", "PyTorch", "Keras", "JAX", "Keras", "Caffe"]

# remove(value) — Removes the FIRST occurrence of the given value. O(n).
# Raises ValueError if the element is not found.
frameworks.remove("Keras")
print(frameworks)  # ['TensorFlow', 'PyTorch', 'JAX', 'Keras', 'Caffe'] — first "Keras" removed

# pop(index) — Removes the element at the given index and RETURNS it. Default: last element.
# pop() (without index) — O(1), pop(i) — O(n)
last = frameworks.pop()       # "Caffe" — removes and returns the last element
second = frameworks.pop(1)    # "PyTorch" — removes the element at index 1
print(last, second)           # Caffe PyTorch
print(frameworks)             # ['TensorFlow', 'JAX', 'Keras']

# del statement — Removes by index or slice. Does not return a value.
del frameworks[0]             # Removes the element at index 0
print(frameworks)             # ['JAX', 'Keras']

# clear() — Removes all elements, leaving an empty list. O(n).
frameworks.clear()
print(frameworks)             # []

Sorting and Searching #

scores = [88, 72, 95, 61, 83, 95, 77]

# sort() — Sorts the list in-place. Timsort algorithm: O(n log n).
# Does not create a new list, modifies the original.
scores.sort()
print(scores)  # [61, 72, 77, 83, 88, 95, 95] — ascending order (default)

scores.sort(reverse=True)
print(scores)  # [95, 95, 88, 83, 77, 72, 61] — descending order

# sorted() — Returns a new sorted list, does not modify the original.
original = [3, 1, 4, 1, 5, 9]
sorted_copy = sorted(original)
print(original)     # [3, 1, 4, 1, 5, 9] — unchanged
print(sorted_copy)  # [1, 1, 3, 4, 5, 9]

# Custom sort criterion using the key parameter
models = [
    {"name": "ModelA", "accuracy": 0.92},
    {"name": "ModelB", "accuracy": 0.87},
    {"name": "ModelC", "accuracy": 0.95},
]
models.sort(key=lambda m: m["accuracy"], reverse=True)
# Sorted in descending order by accuracy

# index(value) — Returns the index of the first occurrence of the element. O(n).
nums = [10, 20, 30, 20, 40]
print(nums.index(20))       # 1 — index of the first 20
# nums.index(99)            # ValueError — when element is not found

# count(value) — Counts how many times the element appears. O(n).
print(nums.count(20))       # 2

# 'in' operator — Checks for the existence of an element. O(n).
print(30 in nums)           # True
print(99 in nums)           # False

2.5 Shallow Copy vs Deep Copy #

This is one of the most commonly confused and bug-causing concepts in Python. Knowing the difference is critical.

Shallow copy — creates a new list, but retains the same references to inner objects as the original list. That is, if an inner element is mutable (e.g., a list inside a list), both copies point to the same inner object.

Deep copy — creates a new list and also creates independent copies of all inner objects. No references are shared.

import copy

# Original: nested list
original = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# === Shallow Copy ===
# Top-level elements are copied, but inner lists REFERENCE THE SAME objects
shallow = original.copy()          # Alternatives: list(original), original[:]
shallow[0][0] = 999                # Modifying the inner list...
print(original[0][0])              # 999! — Original ALSO changed, because they reference the same object

# === Deep Copy ===
original = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  # Restoring the original
deep = copy.deepcopy(original)     # A completely independent copy of everything
deep[0][0] = 999                   # Modifying the inner list...
print(original[0][0])              # 1 — Original did NOT change, because they are independent copies

Shallow Copy vs Deep Copy Comparison Table #

Feature Shallow Copy Deep Copy
Top-level Creates a new object Creates a new object
Inner objects Shares the same reference as the original Creates fully independent copies
Performance Fast — O(n) Slow — O(n·m), n = elements, m = depth
Memory Uses less memory Uses more memory
Use case Flat (single-level) lists Nested structures
Creation .copy(), list(), [:] copy.deepcopy()

[!tip] Best Practice — When is Deep Copy Needed? If your list contains only immutable elements (int, str, tuple, float), a shallow copy is sufficient — immutable elements cannot be changed anyway. Deep copy is only needed when there are mutable inner objects (list, dict, set). In ML, for example, deep copy may be needed when copying a dict of model hyperparameters.


3. Tuples #

3.1 What is a Tuple? #

A tuple is an ordered and immutable data structure. After creation, elements cannot be added, removed, or modified. This immutability is the key characteristic that differentiates a tuple from a list.

Practical benefits of tuple immutability:

  1. Hashable — can be used as a dictionary key or set element (a list cannot)
  2. Thread-safe — no synchronization needed in parallel programming
  3. Less memory — slightly more optimized than a list
  4. Semantic meaning — clearly expresses the intent "this data should not change" in code

3.2 Creating a Tuple #

# Different ways to create a tuple
empty_tuple = ()                           # Empty tuple
single_element = (42,)                     # Single-element tuple — the comma is REQUIRED
without_parens = 42,                       # A tuple can be created without parentheses (tuple packing)
coordinates = (41.0082, 28.9784)           # Istanbul coordinates
mixed = ("Transformer", 2017, ["attention", "feedforward"])  # Different types

# tuple() constructor
from_list = tuple([1, 2, 3])              # From list to tuple: (1, 2, 3)
from_string = tuple("AI")                 # From string to tuple: ('A', 'I')
from_range = tuple(range(5))              # From range to tuple: (0, 1, 2, 3, 4)

# CAUTION: If the comma is forgotten in a single-element tuple, it becomes a value, not a tuple
not_a_tuple = (42)    # This is an int, not a tuple!
is_a_tuple = (42,)    # This is a tuple
print(type(not_a_tuple))  # <class 'int'>
print(type(is_a_tuple))   # <class 'tuple'>

3.3 Tuple Operations #

# Indexing and slicing — same rules as a list
model_info = ("GPT-4", "OpenAI", 2023, 1.76e12)
print(model_info[0])      # "GPT-4"
print(model_info[-1])     # 1760000000000.0
print(model_info[1:3])    # ("OpenAI", 2023) — the result of a slice is also a tuple

# Tuple methods (only 2 methods — because it is immutable)
numbers = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
print(numbers.count(5))   # 3 — the number 5 appears 3 times
print(numbers.index(9))   # 5 — first index of the number 9

# Tuple concatenation — creates a new tuple, originals do not change
part1 = (1, 2, 3)
part2 = (4, 5, 6)
combined = part1 + part2   # (1, 2, 3, 4, 5, 6) — new object
repeated = part1 * 3       # (1, 2, 3, 1, 2, 3, 1, 2, 3)

# Tuples cannot be modified — attempting to do so raises TypeError
# model_info[0] = "GPT-5"  # TypeError: 'tuple' object does not support item assignment

3.4 Tuple Unpacking #

Tuple unpacking is the process of assigning the elements of a tuple to separate variables. This is one of the most powerful and elegant features of Python.

# Simple unpacking
model_name, company, year = ("BERT", "Google", 2018)
print(model_name)   # "BERT"
print(year)         # 2018

# Swapping variable values — no need for a temp variable
a, b = 10, 20
a, b = b, a          # Python does this with tuple unpacking: (b, a) = (20, 10)
print(a, b)          # 20 10

# Collecting remaining elements with * (star)
first, *middle, last = (1, 2, 3, 4, 5)
print(first)    # 1
print(middle)   # [2, 3, 4] — collected as a list
print(last)     # 5

# Returning multiple values from a function (a tuple is actually returned)
def evaluate_model(predictions, labels):
    correct = sum(p == l for p, l in zip(predictions, labels))
    total = len(predictions)
    accuracy = correct / total
    error_rate = 1 - accuracy
    return accuracy, error_rate   # Returns as a tuple: (accuracy, error_rate)

acc, err = evaluate_model([1, 0, 1, 1], [1, 1, 1, 1])
print(f"Accuracy: {acc:.2%}, Error: {err:.2%}")  # Accuracy: 75.00%, Error: 25.00%

# Skipping unused values with '_'
_, _, year = ("BERT", "Google", 2018)
print(year)  # 2018 — only year is needed, we ignore the rest

3.5 Named Tuples #

collections.namedtuple is a more readable version of a tuple. It allows accessing elements by name instead of index, while retaining all the advantages of a tuple (immutability, hashability, memory efficiency).

from collections import namedtuple

# Named tuple definition — creates a new type called ModelConfig
ModelConfig = namedtuple("ModelConfig", ["name", "params", "layers", "accuracy"])

# Creating an object
gpt4 = ModelConfig(
    name="GPT-4",
    params=1.76e12,
    layers=120,
    accuracy=0.945
)

# Accessing elements by name — instead of index
print(gpt4.name)       # "GPT-4" — much more readable
print(gpt4.accuracy)   # 0.945
print(gpt4[0])         # "GPT-4" — index access still works

# Named tuple is immutable
# gpt4.accuracy = 0.96  # AttributeError

# _replace() — creates a new tuple with a change (original does not change)
gpt4_updated = gpt4._replace(accuracy=0.96)
print(gpt4_updated)    # ModelConfig(name='GPT-4', params=1760000000000.0, layers=120, accuracy=0.96)

[!tip] Best Practice — Named Tuple vs Dataclass The @dataclass decorator introduced in Python 3.7+ is a powerful alternative to named tuples. The key difference: dataclasses are mutable by default (but can be made immutable with frozen=True) and offer more functionality (default values, methods, __post_init__). Use named tuples for simple, immutable data containers; use dataclasses for more complex data models.


4. Dictionaries #

4.1 What is a Dictionary? #

A dictionary (dict) is a key-value pair data structure that is ordered (preserves insertion order in Python 3.7+) and mutable. It is internally implemented as a hash table — this ensures that key-based lookups occur with an average O(1) complexity.

Dictionary keys must be hashable — meaning only immutable types (str, int, float, tuple) can be used as keys. Mutable types like list, dict, and set cannot be keys because their hash values can change.

4.2 Creating a Dictionary #

# Literal syntax — the most commonly used way
model_registry = {
    "gpt-4": {"provider": "OpenAI", "params": "1.76T", "type": "LLM"},
    "claude-3": {"provider": "Anthropic", "params": "Unknown", "type": "LLM"},
    "gemini": {"provider": "Google", "params": "Unknown", "type": "Multimodal"},
}

# dict() constructor
config = dict(learning_rate=0.001, epochs=100, batch_size=32)
# {'learning_rate': 0.001, 'epochs': 100, 'batch_size': 32}

# Creating a dict from a list of pairs
pairs = [("name", "ResNet"), ("layers", 50), ("accuracy", 0.93)]
model = dict(pairs)
# {'name': 'ResNet', 'layers': 50, 'accuracy': 0.93}

# dict.fromkeys() — creating multiple keys with the same default value
metrics = dict.fromkeys(["precision", "recall", "f1_score"], 0.0)
# {'precision': 0.0, 'recall': 0.0, 'f1_score': 0.0}

# Creating a dict from two lists using zip()
keys = ["name", "version", "framework"]
values = ["BERT", "base", "PyTorch"]
model_info = dict(zip(keys, values))
# {'name': 'BERT', 'version': 'base', 'framework': 'PyTorch'}

4.3 Accessing Elements #

config = {
    "model": "Transformer",
    "layers": 12,
    "hidden_size": 768,
    "attention_heads": 12,
}

# Direct indexing — raises KeyError if the key does not exist
print(config["model"])     # "Transformer"
# print(config["missing"])  # KeyError: 'missing'

# get() method — returns a default value if the key does not exist (no KeyError)
print(config.get("model"))           # "Transformer"
print(config.get("dropout", 0.1))    # 0.1 — key not found, default returned
print(config.get("missing"))         # None — returns None if no default is provided

[!tip] Best Practice — [] vs get()

  • Use [] when the key must exist — a KeyError helps detect bugs early (fail fast principle).
  • Use get() when the key may or may not exist — especially when reading configurations, processing API responses.
  • Using get() is more Pythonic and efficient than an if key in dict check.

4.4 Dictionary Methods #

# Adding a new key-value / updating an existing one
config = {"model": "BERT", "layers": 12}

config["dropout"] = 0.1                 # Adds a new key
config["layers"] = 24                   # Updates the value of an existing key
print(config)  # {'model': 'BERT', 'layers': 24, 'dropout': 0.1}

# update() — Bulk update from another dict
config.update({"optimizer": "AdamW", "layers": 36})
print(config)  # {'model': 'BERT', 'layers': 36, 'dropout': 0.1, 'optimizer': 'AdamW'}

# Merging with the | operator (Python 3.9+)
defaults = {"lr": 0.001, "epochs": 100}
overrides = {"epochs": 50, "batch_size": 32}
final = defaults | overrides    # overrides takes priority
# {'lr': 0.001, 'epochs': 50, 'batch_size': 32}

# setdefault() — Returns the value if key exists, otherwise adds and returns the default
config.setdefault("scheduler", "cosine")   # "scheduler" doesn't exist, adds it
config.setdefault("model", "GPT")          # "model" already exists, does not change
print(config["scheduler"])  # "cosine"
print(config["model"])      # "BERT" — unchanged

# Deletion operations
removed_value = config.pop("dropout")       # Removes key and returns its value
print(removed_value)                        # 0.1
safe_remove = config.pop("missing", None)   # Returns default if key doesn't exist
last_item = config.popitem()                # Removes and returns the last key-value pair (LIFO)

del config["optimizer"]                     # Deletion with del — does not return a value

4.5 Iterating Over a Dictionary #

hyperparams = {
    "learning_rate": 0.001,
    "batch_size": 32,
    "epochs": 100,
    "dropout": 0.3,
}

# Over keys only (default behavior)
for key in hyperparams:
    print(key)
# learning_rate, batch_size, epochs, dropout

# Over values only
for value in hyperparams.values():
    print(value)
# 0.001, 32, 100, 0.3

# Over key-value pairs (most commonly used)
for key, value in hyperparams.items():
    print(f"{key}: {value}")

# Transforming values with dict comprehension
# Converting all string values to uppercase
metadata = {"name": "bert", "version": "large", "task": "classification"}
upper_metadata = {k: v.upper() for k, v in metadata.items()}
# {'name': 'BERT', 'version': 'LARGE', 'task': 'CLASSIFICATION'}

4.6 defaultdict and Counter #

Special dict types from the collections module are very useful:

from collections import defaultdict, Counter

# defaultdict — automatically creates a default value when a non-existent key is accessed
# Instead of KeyError, a default factory function is called

# Grouping words by category
word_categories = defaultdict(list)   # Default value: empty list []
words = [("noun", "model"), ("verb", "train"), ("noun", "data"), ("verb", "predict")]

for category, word in words:
    # If key doesn't exist, an empty list is automatically created, then appended to
    word_categories[category].append(word)

print(dict(word_categories))
# {'noun': ['model', 'data'], 'verb': ['train', 'predict']}

# defaultdict as a counter
char_count = defaultdict(int)   # Default value: 0
for char in "transformer":
    char_count[char] += 1       # Starts from 0 if not present

print(dict(char_count))
# {'t': 1, 'r': 3, 'a': 1, 'n': 1, 's': 1, 'f': 1, 'o': 1, 'e': 1}

# Counter — special dict for counting elements
predictions = ["positive", "negative", "positive", "neutral", "positive", "negative"]
count = Counter(predictions)
print(count)                        # Counter({'positive': 3, 'negative': 2, 'neutral': 1})
print(count.most_common(2))         # [('positive', 3), ('negative', 2)] — top 2 most common

5. Sets #

5.1 What is a Set? #

A set is an unordered, mutable data structure that stores only unique elements. It is internally implemented as a hash table — this ensures that membership checks (the in operator) and add/remove operations occur with average O(1) complexity.

Set elements must be hashable — meaning only immutable types (int, str, float, tuple) are allowed. Mutable types like list, dict, and other sets cannot be set elements.

5.2 Creating a Set #

# Literal syntax
unique_frameworks = {"TensorFlow", "PyTorch", "JAX", "TensorFlow"}
print(unique_frameworks)   # {'TensorFlow', 'PyTorch', 'JAX'} — duplicates automatically removed

# CAUTION: Using {} to create an empty set is NOT possible — this creates an empty dict!
empty_dict = {}            # This is a DICT, not a set!
empty_set = set()          # The correct way to create an empty set

# set() constructor — removes duplicates from any iterable
numbers = set([1, 2, 2, 3, 3, 3, 4])   # {1, 2, 3, 4}
chars = set("mississippi")              # {'m', 'i', 's', 'p'} — unique characters

5.3 Set Operations #

# Adding and removing elements
skills = {"python", "sql", "git"}

skills.add("docker")           # Adds a single element. O(1).
skills.add("python")           # Already exists — no effect
print(skills)                  # {'python', 'sql', 'git', 'docker'}

skills.update(["kubernetes", "linux"])  # Adds multiple elements
print(skills)                  # {'python', 'sql', 'git', 'docker', 'kubernetes', 'linux'}

skills.remove("sql")           # Removes element. Raises KeyError if not found.
skills.discard("java")         # Removes element. Passes SILENTLY if not found.
popped = skills.pop()          # Removes and returns a random element

5.4 Set Algebra Operations #

The most powerful aspect of a set is mathematical set operations. These operations are extremely useful for data comparison, filtering, and analysis.

# Skill sets of two ML engineers
engineer_a = {"python", "pytorch", "docker", "sql", "kubernetes"}
engineer_b = {"python", "tensorflow", "aws", "sql", "spark"}

# UNION — All unique elements from both sets
all_skills = engineer_a | engineer_b    # or: engineer_a.union(engineer_b)
print(all_skills)
# {'python', 'pytorch', 'docker', 'sql', 'kubernetes', 'tensorflow', 'aws', 'spark'}

# INTERSECTION — Elements common to both sets
common_skills = engineer_a & engineer_b   # or: engineer_a.intersection(engineer_b)
print(common_skills)
# {'python', 'sql'}

# DIFFERENCE — Elements in A but not in B
only_a = engineer_a - engineer_b          # or: engineer_a.difference(engineer_b)
print(only_a)
# {'pytorch', 'docker', 'kubernetes'}

only_b = engineer_b - engineer_a
print(only_b)
# {'tensorflow', 'aws', 'spark'}

# SYMMETRIC DIFFERENCE — Elements in only one of the sets (not in common)
unique_to_each = engineer_a ^ engineer_b  # or: engineer_a.symmetric_difference(engineer_b)
print(unique_to_each)
# {'pytorch', 'docker', 'kubernetes', 'tensorflow', 'aws', 'spark'}
# Set comparison operations
required_skills = {"python", "sql"}
candidate_skills = {"python", "sql", "docker", "pytorch"}

# Subset check — "is required entirely within candidate?"
print(required_skills <= candidate_skills)    # True — issubset()
print(required_skills < candidate_skills)     # True — strict subset (not exactly equal)

# Superset check
print(candidate_skills >= required_skills)    # True — issuperset()

# Disjoint check — "are there no common elements?"
set_a = {1, 2, 3}
set_b = {4, 5, 6}
print(set_a.isdisjoint(set_b))               # True — no common elements

5.5 Frozenset — Immutable Set #

frozenset is the immutable version of a set. It can be used as a dict key or as an element of another set.

# Creating a frozenset
immutable_set = frozenset([1, 2, 3, 4])
# immutable_set.add(5)  # AttributeError — cannot be modified

# Using as a dict key — a regular set cannot do this
permissions = {
    frozenset({"read", "write"}): "Editor",
    frozenset({"read"}): "Viewer",
    frozenset({"read", "write", "admin"}): "Admin",
}

user_perms = frozenset({"read", "write"})
print(permissions[user_perms])  # "Editor"

5.6 Set Operations Comparison Table #

Operation Operator Method Result
Union a | b a.union(b) All elements from both sets
Intersection a & b a.intersection(b) Common elements
Difference a - b a.difference(b) In A but not in B
Symmetric difference a ^ b a.symmetric_difference(b) In only one of them
Subset a <= b a.issubset(b) Is A a subset of B?
Superset a >= b a.issuperset(b) Is A a superset of B?

6. Comparison of Main Data Structures #

6.1 List vs Tuple #

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Mutable? ✅ Yes ❌ No
Hashable? ❌ No ✅ Yes (when elements are hashable)
Can be a dict key? ❌ No ✅ Yes
Performance Slightly slower Slightly faster (immutability optimization)
Memory More (extra space for dynamic resize) Less
Methods 11+ methods 2 methods (count, index)
Use case Dynamic collections, elements can change Fixed data: coordinates, RGB, return values
Semantic meaning "A mutable list of things of the same type" "A fixed group of data of different types"

6.2 List vs Set #

Feature List Set
Ordered? ✅ Yes ❌ No
Duplicates? ✅ Allowed ❌ Unique only
Index access ✅ list[0] ❌ Not possible
in search speed O(n) — slow O(1) — very fast
Element type Any Hashable only
Use case Ordered data, duplicates needed Unique data, fast lookup

6.3 Dictionary vs List of Tuples #

Feature Dictionary List of Tuples
Key-based lookup O(1) O(n)
Ordered? ✅ (3.7+) ✅
Duplicate key? ❌ Last value remains ✅ Allowed
Memory More (hash table overhead) Less
Use case Key-value mapping, fast lookup Ordered pairs, duplicate keys needed

6.4 Time Complexity of Operations #

Operation List Tuple Dict Set
Index access O(1) O(1) — —
Key-based lookup — — O(1) avg —
in (membership check) O(n) O(n) O(1) avg O(1) avg
Append to end O(1) amort. — O(1) avg O(1) avg
Insert at beginning O(n) — — —
Deletion (by value) O(n) — O(1) avg O(1) avg
Sorting O(n log n) — — —

7. Day 2 — Summary #

Topic Key Point
List Ordered, mutable, dynamic array; the most versatile data structure
Tuple Ordered, immutable; for fixed data, can be a dict key
Dictionary Key-value pairs, hash table, O(1) lookup
Set Unique elements, hash table, set algebra operations
Shallow vs Deep Copy Deep copy is needed when there are nested mutable objects
Big-O Choice of data structure directly affects performance

[!note] Next Day In Day 3, we will learn Python's powerful functional tools — List Comprehensions, Generators, and Decorators. These tools enhance the brevity, readability, and memory efficiency of code.