Python data structures organize and manage data efficiently. The four built-in collections are list, tuple, dict, and set.
A list is an ordered, mutable collection that allows duplicates.
fruits = ["apple", "banana", "orange"]fruits.append("mango")fruits.remove("banana")fruits.sort()print(fruits)print(fruits[0])
Common methods: append(), extend(), insert(), remove(), pop(), sort(), and reverse().
A tuple is an ordered, immutable collection that allows duplicates.
coordinates = (10, 20)x, y = coordinatessingle = (42,) # Single-element tuple
Tuples support indexing, slicing, and unpacking but cannot be modified after creation. However, mutable objects inside a tuple can still change.
A dictionary stores key-value pairs. Keys must be hashable, and assigning an existing key updates its value.
user = {"name": "Alice", "age": 25}user["age"] = 26user["city"] = "Hanoi"print(user.get("email")) # Nonefor key, value in user.items():print(key, value)
Common methods: get(), keys(), values(), items(), update(), and pop().
A set stores unique, hashable elements and is useful for removing duplicates and performing mathematical set operations.
a = {1, 2, 3}b = {3, 4, 5}print(a | b) # Unionprint(a & b) # Intersectionprint(a - b) # Differenceprint(a ^ b) # Symmetric difference
Use add() to insert an element and discard() to remove one without raising an error if it is missing. Use set() to create an empty set.
A shallow copy creates a new outer collection but shares references to nested objects. A deep copy recursively copies nested objects where supported.
import copyoriginal = [[1, 2], [3, 4]]shallow = copy.copy(original)deep = copy.deepcopy(original)shallow[0].append(99)print(original) # [[1, 2, 99], [3, 4]]print(deep) # [[1, 2], [3, 4]]
Use shallow copies when sharing nested objects is acceptable, and deep copies when nested data must be independent.
| Structure | Ordered | Mutable | Duplicates |
|---|---|---|---|
list | Yes | Yes | Yes |
tuple | Yes | No | Yes |
dict | Yes* | Yes | Keys: No |
set | No guaranteed order | Yes | No |
*Dictionaries preserve insertion order in modern Python.
Choose the appropriate data structure based on how data needs to be accessed, modified, and organized.