Applied Machine Learning

Python · Beginner

Python Data Structures: Lists, Tuples, Dictionaries, and Sets

Learn to organize and manipulate Python collections with indexing, slicing, and comprehensions.

Applied Machine Learning ·

This is part 2 of the Python Fundamentals series. Complete the preceding tutorial before starting.

Getting started

Use Google Colab to run the examples. See our Colab beginner guide for setup. Download the accompanying notebook and upload it to Colab. Run cells in order.

Learning objectives

Lists

Lists are ordered, mutable collections that allow duplicate values. Use append to add an item and remove to delete the first matching value.

scores = [0.8, 0.9, 0.85]
scores.append(0.95)
scores.remove(0.8)
print(scores)

Indexing and slicing

Index zero selects the first element; negative indices count from the end. A slice includes its start but excludes its stop. The third slice argument controls the step.

values = [10, 20, 30, 40, 50]
print(values[0], values[-1])
print(values[1:4], values[::2], values[::-1])

Mutability and copying

Assignment does not copy a list. Two names can refer to the same object. A shallow copy creates a new outer list, but nested mutable objects remain shared.

original = [1, 2, 3]
alias = original
copy = original.copy()
alias.append(4)
print(original, copy)

Tuples

Tuples are ordered collections whose element references cannot be reassigned. A single-element tuple needs a trailing comma. Unpacking assigns elements to separate names.

shape = (512, 512)
height, width = shape
print(height, width, (1,))

Dictionaries

Dictionaries associate unique hashable keys with values. They preserve insertion order in modern Python. Access a known key with brackets or use get with a default for missing keys.

model = {"name": "baseline", "accuracy": 0.91}
model["accuracy"] = 0.93
print(model["name"], model.get("loss", "Unavailable"))
print(list(model.items()))

Sets

Sets store unique hashable elements and do not support positional indexing. Union combines elements, intersection finds common elements, and difference finds elements exclusive to the first set.

train = {1, 2, 3}
test = {3, 4, 5}
print(sorted(train | test))
print(sorted(train & test))
print(sorted(train - test))

Comprehensions

Comprehensions construct collections from iterable values. An optional condition filters the input. The expression before for determines each output value.

values = [1, 2, 3, 4, 5]
print([x ** 2 for x in values if x % 2 == 0])
print({x: x ** 2 for x in values})

Practical example: dataset records

A list of dictionaries can represent a small dataset. Each dictionary stores one observation. Extract a column using a comprehension and calculate its mean.

records = [{"id": 1, "score": 0.8}, {"id": 2, "score": 0.9}]
scores = [row["score"] for row in records]
print(sum(scores) / len(scores))

Common mistakes

Remember that indices start at zero and slice stops are excluded. Do not assume assignment copies a mutable collection. Missing dictionary keys can raise KeyError.

Practice exercises

  1. Remove duplicate values from [1, 2, 2, 3] and return a sorted list.
  2. Create a dictionary mapping numbers 1 through 4 to their squares.

Exercise solutions

Exercise 1

print(sorted(set([1, 2, 2, 3])))

Exercise 2

print({x: x ** 2 for x in range(1, 5)})

Continue learning

Explore all Python tutorials →