Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Lists, Dicts and Sets

Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables

A shopping list, a map pin, a stamp album and a contact book: Python's four collections with real output, the KeyError and empty-set traps, and type hints that label a variable without locking it.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Lists, Dicts and Sets

What you will learn

  • Choose between a list, tuple, set and dict for a job
  • Add, remove, look up and unpack values in each collection
  • Avoid two traps: KeyError on a missing key and {} being an empty dict
  • Write type hints like dict[str, int] and explain why Python does not enforce them

Before you start

  • Python Data Types, Variables and Strings

So far each variable has held a single value. But a shopping cart has many items, and a student has many details. Python gives you four ways to hold many values in one variable, and once you know them, most Python code gets a lot easier to read.

Before any code, think about four things you already use:

  • A shopping list on paper. Items sit in order, and you can add one or cross one off. That's a list.
  • A pin on a map. Two numbers that belong together, which nobody should change. That's a tuple.
  • A stamp album. You keep one of each, so a second copy adds nothing. That's a set.
  • A contact book. You look up a name and get a number back. That's a dictionary.
Four Python collections: list in square brackets keeps order and changes, tuple in round brackets is fixed, set in curly braces keeps one of each, dict in curly braces with key colon value looks up by key list ["milk", "eggs"] ordered repeats OK can change tuple (3, 4) ordered can't change unpack: x, y set {1, 2, 3} one of each no positions union, intersection dict {"name": "Alice"} key to value each key once [key] or .get()
All four hold many values. The difference is what each one lets you do.

A list keeps things in order

shopping = ["milk", "eggs", "bread"]
item_count = len(shopping)
unit_price = 2.50

shopping.append("cheese")
shopping.remove("bread")
total_cost = item_count * unit_price

print(shopping)
print("First item:", shopping[0])
print("Got milk?", "milk" in shopping)
print(f"Estimated cost: ${total_cost:.2f}")
['milk', 'eggs', 'cheese']
First item: milk
Got milk? True
Estimated cost: $7.50

append adds cheese at the end, and remove finds bread and takes it out. Positions start at 0, so shopping[0] is milk. in asks a yes or no question: is it inside?

Notice one thing. item_count was counted on line two, and it doesn't follow the list. It's still right here only because we added one item and removed one.

Reading and changing a list

colors = ["red", "green", "blue"]

print(colors[0], colors[-1])
print(colors[0:2])

colors[1] = "yellow"
colors.insert(0, "black")
last = colors.pop()
colors.sort()
print(colors)
print(last)
print(len(colors))
red blue
['red', 'green']
['black', 'red', 'yellow']
blue
3

-1 counts from the end, and [0:2] is a slice that stops before index 2. colors[1] = "yellow" replaces green. insert(0, ...) puts black at the front, pop() takes the last item out and hands it back, and sort() puts the list in order. A list keeps its order, allows repeats, and changes in place.

A tuple is a fixed group

point = (3, 4)
single = (7,)

print(point)
print(point[0], point[1])
print(len(point), type(single))

x, y = point
print(x, y)
days = ("Mon", "Tue", "Wed")
print(days[-1])
(3, 4)
3 4
2 <class 'tuple'>
3 4
Wed

Reading works just like a list. A tuple with one value needs that comma; without it, (7) is only a 7 in brackets. x, y = point is unpacking: 3 goes into x and 4 into y in one assignment. You'll see it a lot with coordinates or the red, green and blue values of a colour.

A tuple can't be changed

point = (3, 4)
point[0] = 10
print(point)
Traceback (most recent call last):
  File "S01L05_Collections\tuple_error.py", line 2, in <module>
    point[0] = 10
    ~~~~~^^^
TypeError: 'tuple' object does not support item assignment

That's the reason to use one. If values belong together and shouldn't change, like a location or a box size, a tuple protects them.

A set keeps one of each

numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
print(len(numbers))

numbers.add(4)
numbers.add(2)
print(numbers)
print(3 in numbers)

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
tags = ["new", "sale", "new", "hot", "sale"]
print(sorted(set(tags)))
{1, 2, 3}
3
{1, 2, 3, 4}
True
{1, 2, 3, 4, 5}
{3}
['hot', 'new', 'sale']

Python keeps only one of each, so the length is 3, not 6. Adding 2 again does nothing, with no error. The pipe | is union (everything from both), and & is intersection (only what's in both).

The everyday use is the last line: set(tags) removes repeats, and since a set doesn't promise any order, sorted gives you back a tidy list. A set has no positions either, so numbers[0] isn't allowed. Whenever you hear "unique values", think of a set.

A dictionary looks up by key

student = {"name": "Alice", "age": 21}

print(student["name"])
print(student.get("age"))
print(student.get("grade"))
print(student.get("grade", "not set"))

student["grade"] = "A"
student["age"] = 22
print(student)
print(student.keys())
print(student.values())
print("name" in student)
student.pop("age")
print(student)
Alice
21
None
not set
{'name': 'Alice', 'age': 22, 'grade': 'A'}
dict_keys(['name', 'age', 'grade'])
dict_values(['Alice', 22, 'A'])
True
{'name': 'Alice', 'grade': 'A'}

You ask by key, not by position. get is the second way to ask; for a key that isn't there, it hands back None (nothing there), or the default you give it. Writing to a new key adds it; writing to an existing key replaces the value, because each key appears only once. in on a dict checks the keys, not the values, and pop removes a key with its value.

When a key is missing

student = {"name": "Alice", "age": 21}
print(student["name"])
print(student["grade"])
Alice
Traceback (most recent call last):
  File "S01L05_Collections\dict_missing_key.py", line 3, in <module>
    print(student["grade"])
          ~~~~~~~^^^^^^^^^
KeyError: 'grade'

The rule: if you're sure the key is there, use square brackets. If it might be missing, use get.

The empty set trap

empty_list = []
empty_tuple = ()
empty_dict = {}
empty_set = set()
wrong_set = {}

print(type(empty_list))
print(type(empty_tuple))
print(type(empty_dict))
print(type(empty_set))
print(type(wrong_set))
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'dict'>

Someone wanted a set and wrote {}. Python says dict, and nothing warns you. Empty curly braces are an empty dictionary; set() is an empty set.

Type hints: a label on a box

Think about a storage box with a label that says books. The label tells everyone what's meant to be inside without opening it. It doesn't lock anything, though; someone can still put shoes in. But anyone checking can compare the contents with the label and point out that shoes don't belong. A type hint is that label, on a variable.

name: str = "Alice"
age: int = 21
price: float = 2.50
fruits: list[str] = ["apple", "banana"]
point: tuple[int, int] = (3, 4)
tags: set[str] = {"new"}
scores: dict[str, int] = {"maths": 90, "art": 75}

print(name, age, price)
print(fruits, point, tags)
print(scores)
Alice 21 2.5
['apple', 'banana'] (3, 4) {'new'}
{'maths': 90, 'art': 75}

A colon and a type go between the name and the value. list[str] is a list of strings, tuple[int, int] two whole numbers, and dict[str, int] string keys with whole-number values.

Python doesn't enforce hints

age: int = "twenty-one"
scores: dict[str, int] = {"maths": "high"}

print(age)
print(scores)
print(type(age))
twenty-one
{'maths': 'high'}
<class 'str'>

No error. The value decides the type, not the hint. Hints are there for people and tools: you, when you come back to the code later; PyCharm, which can warn you about a value that doesn't match and suggest the right methods; type checkers that read a whole project; and AI tools, which read hints as context about the shape of your data.

You can ask for them, too. A sample prompt: "Create a beginner Python example focused on list operations for a shopping scenario, and use type hints on variables." Then read what comes back. Hints on functions come later, in Type hints on functions.

All four together

prices: dict[str, float] = {
    "milk": 1.50,
    "eggs": 3.00,
    "bread": 2.25,
}
cart: list[str] = ["milk", "eggs", "milk"]
unique: set[str] = set(cart)
dims: tuple[int, int] = (30, 20)

print(len(cart), "items,", len(unique), "different")
print("Price of milk:", prices["milk"])
print("Price list total:", sum(prices.values()))
print("Has cheese?", "cheese" in prices)
print("Box size:", dims[0], "x", dims[1])
3 items, 2 different
Price of milk: 1.5
Price list total: 6.75
Has cheese? False
Box size: 30 x 20

Prices are a dict because you look a price up by name. The cart is a list because order matters and repeats are fine (milk is there twice). unique is a set, so the repeat drops out. dims is a tuple because a box size is a fixed pair. Careful with the total: 6.75 is every price on the list once, not the cost of this cart.

Quick recap

You needUseWrite
order and changeslist["a", "b"]
fixed valuestuple(3, 4), (7,)
no repeatsset{1, 2}, empty: set()
look up by keydict{"k": v}, empty: {}
a label for readers and toolstype hintscores: dict[str, int]

Try it yourself

In the cart example, add a stock dictionary with the hint dict[str, int], and read one value with get. Or prompt an AI tool to write it, then read every line it gives you.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 16 of 48

Previous
Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
Next post
Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops

A comprehension is a small loop folded into one line. Every form is shown beside the loop it replaces: lists, the if at the end versus if/else at the front, dicts, sets, two fors, generator expressions, and when to go back to a loop.

On this page

  • A list keeps things in order
  • Reading and changing a list
  • A tuple is a fixed group
  • A tuple can't be changed
  • A set keeps one of each
  • A dictionary looks up by key
  • When a key is missing
  • The empty set trap
  • Type hints: a label on a box
  • Python doesn't enforce hints
  • All four together
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.