micheledpierri.com

  • HOME
    • Python
    • Statistics
    • Data Analysis
    • Machine Learning
  • WRITINGS
  • VISIONS
  • ABOUT
Home / Python / Collections: Lists, Tuples, Sets, and Dictionaries
Children dressed in lab coats are studying a python

Collections: Lists, Tuples, Sets, and Dictionaries

Lesson Objectives

By the end of this lesson, you will be able to:

  • Understand what Python collections are and why they matter
  • Use lists, tuples, sets, and dictionaries appropriately
  • Choose the right data structure for a given problem
  • Recognize how these structures map to real-world data

This lesson is fundamental:

most data analysis and machine learning workflows are built on these four structures.


1️⃣ What Is a Collection

A collection is a container that stores multiple values under a single name.

Instead of writing:

age1 =54
age2 =67
age3 =61

you can write:

ages = [54,67,61]

Collections allow you to:

  • group related data
  • iterate over values
  • apply transformations systematically

2️⃣ Lists (list)

Lists are ordered, mutable collections.

ages = [54,67,61]

Key properties:

  • ordered (positions matter)
  • mutable (can be changed)
  • allow duplicates

Common List Operations

ages.append(45) # add element
ages[0] # access by index
len(ages) # number of elements

Indexes start from 0.

Lists in Data Analysis

Lists are used to:

  • store observations
  • accumulate results
  • iterate over datasets

They are often the first step before more advanced structures (e.g. DataFrames).


3️⃣ Tuples (tuple)

Tuples are ordered but immutable collections.

patient = ("P001",54,"M")

Key properties:

  • ordered
  • immutable (cannot be modified)
  • allow duplicates

Why Use Tuples

Tuples are useful when:

  • data should not change
  • structure is fixed
  • values belong together

Example:

(x, y) = (3,5)

This is common in mathematical and statistical code.


4️⃣ Sets (set)

Sets are unordered collections of unique elements.

risk_factors = {"smoker","hypertension","diabetes"}

Key properties:

  • unordered
  • no duplicates
  • fast membership testing

Set Operations

"a"in risk_factors

set1 | set2 # union
set1 & set2 # intersection

Sets in Data Analysis

Sets are ideal for:

  • removing duplicates
  • comparing groups
  • checking membership

They are conceptually very close to mathematical sets.


5️⃣ Dictionaries (dict)

Dictionaries store key–value pairs.

patient = {
"id":"P001",
"age":54,
"sex":"M"
}

Keys are unique; values can be anything.

Accessing Dictionary Values

patient["age"]
patient.get("age")

Difference:

  • [] raises an error if missing
  • .get() returns None

Dictionaries in Data Analysis

Dictionaries are ubiquitous because they map naturally to:

  • records
  • rows
  • JSON objects
  • structured observations

Most real-world data starts its life as dictionaries.


6️⃣ Choosing the Right Collection

A practical rule of thumb:

  • list → ordered sequence of values
  • tuple → fixed group of values
  • set → unique values, membership logic
  • dict → structured records with named fields

Choosing the right structure simplifies code dramatically.


7️⃣ Iterating Over Collections

Collections become powerful when combined with loops.

for age in ages:
	print(age)

for key, value in patient.items():
	print(key, value)

Iteration is the backbone of data processing.


8️⃣ Collections and Real Data

In practice:

  • a dataset → list of dictionaries
  • a row → dictionary
  • a column → list
  • categories → set

This mental model will reappear later with pandas and machine learning pipelines.


FAQ — Frequently Asked Questions

Q: Why not use only lists?

A: Different problems require different guarantees (order, mutability, uniqueness).

Q: Are dictionaries ordered?

A: Yes (since Python 3.7), but conceptually they are still key–value mappings.

Q: Can dictionary values be collections?

A: Yes. Nested structures are extremely common.

Q: Should I memorize all methods?

A: No. Understand concepts first; methods come naturally.


Exercises

Exercise 1

Create a list of ages.

Exercise 2

Add a new age to the list.

Exercise 3

Access the first element of the list.

Exercise 4

Create a tuple representing a patient (id, age, sex).

Exercise 5

Explain why tuples cannot be modified.

Exercise 6

Create a set of risk factors with duplicates.

Exercise 7

Show that duplicates are removed.

Exercise 8

Create a dictionary representing a patient.

Exercise 9

Access a value safely using .get().

Exercise 10

Explain which collection you would use to represent a dataset of patients.


Solutions

Exercise 1

ages = [54,67,61]

Exercise 2

ages.append(45)

Exercise 3

ages[0]

Exercise 4

patient = ("P001",54,"M")

Exercise 5

# Tuples are immutable to protect fixed structure

Exercise 6

risk_factors = {"smoker","smoker","diabetes"}

Exercise 7

# Only unique elements remain

Exercise 8

patient = {"id":"P001","age":54,"sex":"M"}

Exercise 9

patient.get("age")

Exercise 10

# A dataset is best represented as a list of dictionaries


Next Lesson Preview

In Lesson 8, we will move from single files to structured code:

  • modules
  • packages
  • reading and writing files

This is where Python projects start to look like real software.

Cite this article

Pierri, M. D. (2026). Collections: Lists, Tuples, Sets, and Dictionaries. micheledpierri.com. Permalink

Share:Email·LinkedIn
Previous← Functions and Code ReusabilityNextModules, Packages, and File Handling →
Python
  1. Why Python
  2. Python & VS Code Setup (From Zero to a Professional Environment)
  3. Variables, Naming Rules, and Basic Syntax
  4. Core Data Types in Python
  5. Control Flow: Conditions and Loops
  6. Functions and Code Reusability
  7. Collections: Lists, Tuples, Sets, and Dictionaries
  8. Modules, Packages, and File Handling
  9. Errors, Exceptions, and Robust Code
  10. Object-Oriented Programming (OOP) in Python
  11. Intermediate Python: Writing Clean, Pythonic Code
  12. Python Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step)
© 2024–2026 micheledpierri.com · Privacy Policy · Impressum