TechLead
Lesson 5 of 25
5 min read
Python

Lists, Tuples, Sets, and Dicts

Deep dive into Python's core collection types, their methods, and when to use each one

Lists

Lists are ordered, mutable sequences that can hold items of any type. They are the most versatile and commonly used data structure in Python. Lists support indexing, slicing, and a rich set of methods for adding, removing, and rearranging elements.

# Creating lists
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True, None]
nested = [[1, 2], [3, 4], [5, 6]]

# Accessing elements
print(numbers[0])     # 1 (first)
print(numbers[-1])    # 5 (last)
print(numbers[1:3])   # [2, 3] (slice)
print(numbers[::2])   # [1, 3, 5] (every other)

# Modifying lists
numbers.append(6)          # [1, 2, 3, 4, 5, 6]
numbers.insert(0, 0)       # [0, 1, 2, 3, 4, 5, 6]
numbers.extend([7, 8, 9])  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.remove(0)          # removes first occurrence of 0
popped = numbers.pop()     # removes and returns last element (9)
popped = numbers.pop(0)    # removes and returns element at index 0

# List operations
a = [1, 2, 3]
b = [4, 5, 6]
combined = a + b         # [1, 2, 3, 4, 5, 6]
repeated = a * 3         # [1, 2, 3, 1, 2, 3, 1, 2, 3]
print(3 in a)            # True
print(len(a))            # 3

# Sorting
items = [3, 1, 4, 1, 5, 9, 2, 6]
items.sort()                  # In-place sort: [1, 1, 2, 3, 4, 5, 6, 9]
items.sort(reverse=True)      # [9, 6, 5, 4, 3, 2, 1, 1]
sorted_items = sorted(items)  # Returns new sorted list

# Sort by custom key
words = ["banana", "apple", "cherry", "date"]
words.sort(key=len)  # Sort by length: ['date', 'apple', 'banana', 'cherry']

# Unpacking
first, *rest = [1, 2, 3, 4, 5]
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

first, *middle, last = [1, 2, 3, 4, 5]
print(middle)  # [2, 3, 4]

Tuples

Tuples are ordered, immutable sequences. Once created, their elements cannot be changed. Tuples are used for fixed collections of items, as dictionary keys (since they are hashable), and for returning multiple values from functions. They are slightly more memory-efficient than lists.

# Creating tuples
empty = ()
single = (42,)       # Note the comma! (42) is just an int
coordinates = (3, 4)
rgb = (255, 128, 0)

# Tuple unpacking
x, y = coordinates
r, g, b = rgb
print(f"x={x}, y={y}")

# Named tuples - tuples with named fields
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)     # 3 4
print(p[0], p[1])   # 3 4

# Tuples as dictionary keys (lists cannot be used as keys)
locations = {
    (40.7128, -74.0060): "New York",
    (51.5074, -0.1278): "London",
    (35.6762, 139.6503): "Tokyo",
}
print(locations[(40.7128, -74.0060)])  # "New York"

# Tuple methods
t = (1, 2, 3, 2, 1)
print(t.count(2))  # 2
print(t.index(3))  # 2

Sets

Sets are unordered collections of unique elements. They are highly optimized for membership testing, removing duplicates, and mathematical set operations like union, intersection, and difference. Sets require their elements to be hashable.

# Creating sets
empty = set()         # NOT {} (that creates a dict)
numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

# Adding and removing
numbers.add(6)
numbers.discard(1)   # Remove if present, no error if missing
numbers.remove(2)    # Remove if present, KeyError if missing

# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)   # Union: {1, 2, 3, 4, 5, 6, 7, 8}
print(a & b)   # Intersection: {4, 5}
print(a - b)   # Difference: {1, 2, 3}
print(a ^ b)   # Symmetric difference: {1, 2, 3, 6, 7, 8}

# Subset and superset
print({1, 2} <= {1, 2, 3})  # True (subset)
print({1, 2, 3} >= {1, 2})  # True (superset)

# Practical: remove duplicates while preserving order
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
seen = set()
unique = []
for item in items:
    if item not in seen:
        seen.add(item)
        unique.append(item)
print(unique)  # [3, 1, 4, 5, 9, 2, 6]

# Frozen sets (immutable sets - can be used as dict keys)
fs = frozenset([1, 2, 3])

Dictionaries

Dictionaries are ordered (since Python 3.7+) mappings of keys to values. They provide O(1) average-case lookup by key. Dictionaries are fundamental to Python — they power variable namespaces, class attributes, and much of Python's internals.

# Creating dictionaries
empty = {}
person = {"name": "Alice", "age": 30, "city": "NYC"}
from_pairs = dict([("a", 1), ("b", 2)])
from_kwargs = dict(name="Alice", age=30)

# Accessing values
print(person["name"])         # "Alice"
print(person.get("email"))    # None (no KeyError)
print(person.get("email", "N/A"))  # "N/A" (with default)

# Modifying
person["email"] = "alice@example.com"  # Add/update
del person["city"]                      # Delete
age = person.pop("age")                # Remove and return

# Dictionary methods
print(person.keys())     # dict_keys(['name', 'email'])
print(person.values())   # dict_values(['Alice', 'alice@example.com'])
print(person.items())    # dict_items([('name', 'Alice'), ('email', '...')])

# Merging dictionaries
defaults = {"color": "blue", "size": "medium", "count": 1}
overrides = {"color": "red", "count": 5}

# Python 3.9+ merge operator
merged = defaults | overrides  # {'color': 'red', 'size': 'medium', 'count': 5}

# Unpacking merge (works in Python 3.5+)
merged = {**defaults, **overrides}

# setdefault - get value or set and return default
cache = {}
cache.setdefault("key", []).append("value1")
cache.setdefault("key", []).append("value2")
print(cache)  # {'key': ['value1', 'value2']}

# defaultdict for automatic defaults
from collections import defaultdict

word_count = defaultdict(int)
for word in "the cat sat on the mat".split():
    word_count[word] += 1
print(dict(word_count))  # {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}

When to Use Which Collection

  • List: Ordered items you need to modify, access by index, or iterate in order
  • Tuple: Fixed collections, function return values, dictionary keys, or when immutability is desired
  • Set: Unique items, membership testing, or mathematical set operations
  • Dict: Key-value mappings, lookups by key, caching, or counting

Continue Learning