Data Types and Structures in Python
Python's built-in collections cover many everyday data tasks. Choose a structure for its semantics, not just its syntax.
Lists: ordered and mutable
Lists preserve order and support indexed access, slicing, and in-place changes.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.insert(1, "kiwi")
fruits.remove("banana")
last_fruit = fruits.pop()
fruits[0] = "mango"
print(fruits) # ['mango', 'kiwi', 'cherry']
print(last_fruit) # orange
remove(value) raises ValueError when the value is absent; pop(index) removes and returns an item and raises IndexError for an invalid index.
Tuples: ordered and immutable
Tuples cannot have their items reassigned. They are useful for fixed records and unpacking. Parentheses improve readability, but the comma creates a tuple; a one-item tuple therefore needs a trailing comma.
point = (3, 5)
x, y = point
single = ("only",)
print(x, y) # 3 5
print(len(single)) # 1
Immutability is shallow: a tuple itself cannot be changed, but it may contain a mutable object such as a list.
Dictionaries: key-value mappings
Dictionaries map unique, hashable keys to values and preserve insertion order. Assigning an existing key replaces its value.
record = {"name": "Alice", "age": 30}
record["city"] = "Berlin"
record["age"] = 31
city = record.pop("city")
print(record) # {'name': 'Alice', 'age': 31}
print(city) # Berlin
record[key] raises KeyError for a missing key. Use record.get(key, default) when absence is expected and a default is meaningful.
Sets: unique, unordered values
Sets support membership tests and mathematical set operations. Their iteration and printed order should not be treated as stable. Use set(), not {}, for an empty set.
observed = {"red", "blue", "red"}
allowed = {"blue", "green"}
print(sorted(observed)) # ['blue', 'red']
print(sorted(observed & allowed)) # ['blue']
print(sorted(observed - allowed)) # ['red']
Set elements and dictionary keys must be hashable. Immutable values such as strings and suitable tuples are common choices; lists are not hashable.
Choosing a collection
| Need | Typical choice |
|---|---|
| Ordered sequence that changes | list |
| Fixed ordered record or unpacking | tuple |
| Lookup by unique key | dict |
| Unique values or set algebra | set |
DataFrames are provided by pandas rather than Python itself and are covered in the dedicated pandas fundamentals section.