Lists, Tuples, and Dictionaries
Python gives you several powerful ways to organize and store data. Lists, tuples, and dictionaries are the three most important collection types you’ll use in virtually every program you write. Understanding how each one works—and knowing when to reach for which—will make your code cleaner, faster, and easier to maintain.
In this tutorial, you’ll learn how to create, access, modify, and iterate over each of these data structures. By the end, you’ll have a solid grasp of when to use lists for ordered sequences, tuples for immutable data, and dictionaries for key-value lookups.
Lists: Your Go-To Ordered Collection
Lists are the workhorse of Python data structures. They’re ordered, mutable collections that can hold items of any type. Think of a list as a shopping list—you can add items, remove them, and change the order.
Creating Lists
Creating a list is straightforward. Use square brackets and separate items with commas:
# A list of fruits
fruits = ["apple", "banana", "cherry"]
# A list of mixed types
mixed = [1, "hello", 3.14, True]
# An empty list
empty = []
# Using the list() constructor
numbers = list(range(5)) # [0, 1, 2, 3, 4]
Accessing List Items
Each item in a list has an index, starting from zero. Use square brackets to access individual items:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # "apple" (first item)
print(fruits[1]) # "banana" (second item)
print(fruits[-1]) # "date" (last item)
print(fruits[-2]) # "cherry" (second-to-last)
You can also slice lists to get multiple items at once:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[1:4]) # ["banana", "cherry", "date"]
print(fruits[:3]) # ["apple", "banana", "cherry"]
print(fruits[2:]) # ["cherry", "date", "elderberry"]
print(fruits[::2]) # ["apple", "cherry", "elderberry"] (every second item)
Modifying Lists
Lists are mutable, meaning you can change them after creation:
fruits = ["apple", "banana", "cherry"]
# Change an item
fruits[0] = "avocado"
print(fruits) # ["avocado", "banana", "cherry"]
# Add items
fruits.append("date") # Add to end
fruits.insert(1, "apricot") # Insert at index 1
fruits.extend(["elderberry", "fig"]) # Add multiple items
print(fruits) # ["avocado", "apricot", "banana", "cherry", "date", "elderberry", "fig"]
# Remove items
fruits.pop() # Remove and return last item
fruits.remove("banana") # Remove first occurrence
del fruits[0] # Delete item at index
print(fruits) # ["apricot", "cherry", "date", "elderberry"]
Useful List Operations
Python provides many built-in functions for working with lists:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8 (length)
print(sum(numbers)) # 31 (sum of numbers)
print(max(numbers)) # 9 (maximum)
print(min(numbers)) # 1 (minimum)
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 6, 9] (new sorted list)
# Check membership
print(5 in numbers) # True
print(7 in numbers) # False
Iterating Over Lists
You’ll often need to loop through list items:
fruits = ["apple", "banana", "cherry"]
# Simple iteration
for fruit in fruits:
print(fruit)
# With index using enumerate()
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Using list comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Tuples: Immutable Ordered Collections
Tuples are like lists, but with one key difference: they’re immutable. Once you create a tuple, you cannot change it. Use tuples when you want to ensure data isn’t accidentally modified—common in function return values and dictionary keys.
Creating Tuples
Use parentheses (or just commas) to create tuples:
# Using parentheses
point = (10, 20)
rgb = (255, 128, 0)
# Without parentheses (tuple packing)
coordinates = 10, 20, 30
# Single item tuple (note the comma)
single = ("hello",) # Without comma, it's just a string
# Empty tuple
empty = ()
# Using tuple() constructor
text = tuple("hello") # ('h', 'e', 'l', 'l', 'o')
Accessing Tuple Items
Tuple indexing and slicing work exactly like lists:
point = (10, 20, 30)
print(point[0]) # 10
print(point[-1]) # 30
print(point[1:3]) # (20, 30)
Tuple Unpacking
One of tuples’ most powerful features is unpacking—assigning elements to multiple variables at once:
# Basic unpacking
point = (10, 20, 30)
x, y, z = point
print(x, y, z) # 10 20 30
# Swap values without temporary variable
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# Extended unpacking (Python 3.x)
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Use _ for unused values
rgb = (255, 128, 0)
red, green, _ = rgb
When to Use Tuples
Tuples are perfect for:
- Returning multiple values from functions
- Dictionary keys (lists cannot be keys because they’re mutable)
- Fixed collections that shouldn’t change
- Named constants or configuration values
# Function returning multiple values
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
minimum, maximum, total = get_stats([1, 2, 3, 4, 5])
print(f"Min: {minimum}, Max: {maximum}, Total: {total}")
Dictionaries: Key-Value Pairs
Dictionaries store data as key-value pairs. They provide fast lookup by key—much faster than searching through a list. Think of a dictionary like a real-world dictionary: you look up a word (key) to find its definition (value).
Creating Dictionaries
Use curly braces with key-value pairs:
# Basic dictionary
person = {
"name": "Alice",
"age": 30,
"city": "London"
}
# Using dict() constructor
person = dict(name="Alice", age=30, city="London")
# Empty dictionary
empty = {}
Accessing Dictionary Values
Access values using square brackets with the key, or the .get() method:
person = {"name": "Alice", "age": 30, "city": "London"}
# Using brackets (raises KeyError if key doesn't exist)
print(person["name"]) # "Alice"
# Using .get() (returns None if key doesn't exist)
print(person.get("name")) # "Alice"
print(person.get("country")) # None
# Provide default value
print(person.get("country", "Unknown")) # "Unknown"
Modifying Dictionaries
Dictionaries are mutable—you can add, change, and remove entries:
person = {"name": "Alice", "age": 30}
# Add new key-value pair
person["city"] = "London"
print(person) # {"name": "Alice", "age": 30, "city": "London"}
# Update with another dictionary
person.update({"age": 31, "country": "UK"})
print(person) # {"name": "Alice", "age": 31, "city": "London", "country": "UK"}
# Remove entries
del person["country"] # Delete specific key
age = person.pop("age") # Remove and return value
print(person) # {"name": "Alice", "city": "London"}
# Clear all entries
person.clear()
print(person) # {}
Dictionary Views and Iteration
You can iterate over keys, values, or both:
person = {"name": "Alice", "age": 30, "city": "London"}
# Iterate over keys
for key in person:
print(key)
# Iterate over values
for value in person.values():
print(value)
# Iterate over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Check if key exists
print("name" in person) # True
print("country" in person) # False
Useful Dictionary Operations
# Get all keys, values, or items
person = {"name": "Alice", "age": 30, "city": "London"}
print(list(person.keys())) # ["name", "age", "city"]
print(list(person.values())) # ["Alice", 30, "London"]
print(list(person.items())) # [("name", "Alice"), ("age", 30), ("city", "London")]
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Merge dictionaries (Python 3.9+)
a = {"x": 1}
b = {"y": 2}
merged = a | b
print(merged) # {"x": 1, "y": 2}
Choosing the Right Data Structure
Now you understand all three. But when should you use each?
| Use Case | Data Structure | Why |
|---|---|---|
| Ordered collection that changes | List | Mutable, supports append/pop/insert |
| Fixed ordered data | Tuple | Immutable, slightly faster, hashable |
| Fast lookup by key | Dictionary | O(1) lookup time vs O(n) for lists |
| Collection of unique items | Set (not covered here) | Automatic duplicate handling |
| Key-value associations | Dictionary | Designed for this use case |
Quick Decision Guide
- Need to modify the collection? Use a list.
- Need the collection as a dictionary key or in a set? Use a tuple.
- Need to look up items by name/ID? Use a dictionary.
- Need to ensure data isn’t accidentally changed? Use a tuple.
- Need to store multiple values and iterate in order? Use a list.
Next Steps
Now that you understand these fundamental data structures, you’re ready to move on to the next tutorial in the series. In the next lesson, you’ll learn about modules and imports—how to organize your code across multiple files and use the vast Python standard library.
Continue your learning journey with: Modules and Imports