Chapter 2 · Python Basics
Lists, Tuples, Dictionaries and Sets
- Page 5 of 20
- 4 min read
Real data comes in groups: a list of documents, a chat history, the settings for an API call. Python has four built-in collections to hold them. If you understand these four, you can read the data that AI APIs send and receive.
| Type | Looks like | Ordered? | Changeable? | Use it for |
|---|---|---|---|---|
list | [1, 2, 3] | Yes | Yes | A sequence of items: documents, scores, messages |
tuple | (1, 2) | Yes | No | A fixed group: a coordinate, a (name, score) pair |
dict | {"a": 1} | Yes (insertion order) | Yes | Named fields: one message, one config |
set | {1, 2} | No | Yes | Unique items, fast "is it in?" checks |
Lists
A list holds items in order inside square brackets. Indexing and slicing work exactly as with strings — but unlike strings, lists can be changed:
models = ["gpt-5.5", "claude-opus-5-5", "gemini"]
print(models[0]) # first item
print(len(models)) # how many items
models.append("llama") # add to the end
models[2] = "gemini-pro" # replace an item
models.remove("llama") # remove by value
print(models)
print("claude-opus-5-5" in models)
print(sorted([3, 1, 2]))
print(sum([10, 20, 30]), max([4, 9, 2]), min([4, 9, 2]))gpt-5.5
3
['gpt-5.5', 'claude-opus-5-5', 'gemini-pro']
True
[1, 2, 3]
60 9 2Tuples
A tuple is like a list that cannot change. Use one when the group has a fixed meaning. You can unpack a tuple into separate variables in one line:
point = (23.81, 90.41) # latitude, longitude of Dhaka
lat, lon = point # unpacking
print(lat, lon)
point[0] = 0 # tuples cannot be changed23.81 90.41
Traceback (most recent call last):
File "main.py", line 5, in <module>
point[0] = 0 # tuples cannot be changed
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentDictionaries
A dictionary (dict) stores key → value pairs. You look values up by key instead of by position. This is the most important collection for AI work, because the JSON that every AI API uses becomes dictionaries in Python:
message = {"role": "user", "content": "What is a token?"}
print(message["role"])
print(message.get("name", "anonymous")) # a default if the key is missing
message["content"] = "Explain tokens simply."
message["language"] = "en" # add a new key
print(message)
for key, value in message.items():
print(key, "->", value)user
anonymous
{'role': 'user', 'content': 'Explain tokens simply.', 'language': 'en'}
role -> user
content -> Explain tokens simply.
language -> enmessage["name"] would crash with a KeyError if the key does not exist; message.get("name", default) returns the default instead. Use .get() whenever a key might be missing — for example in data that came from the internet.
Nesting: lists of dictionaries
Collections can contain other collections. This exact shape — a list of message dictionaries — is how a chat conversation is sent to an LLM:
conversation = [
{"role": "system", "content": "You are a helpful tutor."},
{"role": "user", "content": "What is Python?"},
{"role": "assistant", "content": "A popular programming language."},
]
print(len(conversation))
print(conversation[1]["content"])
print(conversation[-1]["role"])3
What is Python?
assistantRead conversation[1]["content"] from left to right: take item 1 of the list (a dict), then its "content" value.
Sets
A set keeps only unique items. Turning a list into a set is the quickest way to remove duplicates, and sets support maths-style operations:
words = "the cat and the dog and the bird".split()
unique = set(words)
print(len(words), len(unique))
print(sorted(unique))
seen_a = {"python", "numpy", "pandas"}
seen_b = {"pandas", "pytorch"}
print(seen_a & seen_b) # in both
print(sorted(seen_a | seen_b)) # in either8 5
['and', 'bird', 'cat', 'dog', 'the']
{'pandas'}
['numpy', 'pandas', 'python', 'pytorch']Sets have no order, which is why we wrapped the set in sorted() before printing it.
A trap: two names, one list
Assigning a list to a new variable does not copy it. Both names point to the same list:
a = [1, 2, 3]
b = a # b is another name for the SAME list
b.append(4)
print(a)
c = a.copy() # a separate copy
c.append(5)
print(a, c)[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]When you need an independent copy, use .copy() (or list(a)). The same is true for dictionaries.
Try it yourself
- Make a dictionary describing yourself (
name,city,skills— where skills is a list) and print one of your skills. - Build a conversation list with a system message and two user messages, then print only the user messages' content.
- Given
tags = ["ai", "python", "ai", "data", "python"], print the unique tags in alphabetical order.