Python Data Structures
Storing Collections of Data
Python provides several powerful built-in data structures for storing collections of data. Mastering them is essential for writing effective Python code. Each has unique properties and is suited for different tasks.
Lists
A list is a collection which is ordered and changeable (mutable). Lists allow duplicate members and are Python's version of a dynamic array. They are one of the most versatile data types.
- Indexing & Slicing: Access elements with
my_list[i]
and ranges withmy_list[start:stop:step]
. - Common Methods:
.append(item)
,.insert(i, item)
,.pop(i)
,.remove(item)
,.sort()
,.reverse()
. - List Comprehensions: A concise way to create lists. For example,
squares = [x*x for x in range(10)]
creates a list of the first 10 squares.
my_list = ["apple", "banana", "cherry"]
my_list.append("orange") # Add item to end -> ['apple', 'banana', 'cherry', 'orange']
my_list[1] = "mango" # Change an item -> ['apple', 'mango', 'cherry', 'orange']
print(my_list[1:3]) # Slicing -> ['mango', 'cherry']
Tuples
A tuple is a collection which is ordered and unchangeable (immutable). Tuples allow duplicate members and are written with round brackets.
Because they are immutable, they can be used as keys in a dictionary, unlike lists. They are also generally slightly more memory-efficient than lists.
- Use Cases: Use tuples for data that should not change, like coordinates (x, y), or for returning multiple values from a function.
- Unpacking: You can assign the values of a tuple to multiple variables at once. e.g.,
x, y = (10, 20)
.
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0]) # Access items like a list
# my_tuple[0] = "mango" -> This would cause a TypeError!
Sets
A set is a collection which is unordered, unindexed, and has no duplicate members. They are highly optimized for membership testing.
Sets support powerful mathematical operations like union, intersection, difference, and symmetric difference.
- Common Methods:
.add(item)
,.remove(item)
(raises error if not found),.discard(item)
(does nothing if not found),.pop()
. - Set Operations: Use operators (
|
for union,&
for intersection) or methods (.union()
,.intersection()
).
my_set = {"apple", "banana", "cherry"}
my_set.add("apple") # Does nothing, as "apple" is already in the set
print("banana" in my_set) # Fast membership testing -> True
Dictionaries
A dictionary is a collection which is ordered (as of Python 3.7), changeable, and does not allow duplicate keys. They store data in key-value pairs and are optimized for retrieving values when the key is known.
- Accessing Items: Use square brackets
my_dict['key']
(raises error if key not found) or the.get('key')
method (returnsNone
or a default value if not found). - Iterating: You can iterate over keys, values, or both using
.keys()
,.values()
, and.items()
.
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
my_dict["year"] = 2024 # Change a value
my_dict["color"] = "red" # Add a new key-value pair
print(my_dict.get("model"))
Interactive Simulations
While Python's high-level data structures like lists and dictionaries are incredibly powerful, they are built on top of more fundamental concepts like arrays and linked lists. Understanding how these underlying structures work will give you a much deeper appreciation for their performance characteristics.
In Python, a list
is implemented as a dynamic array. A dictionary is implemented using a hash table. Explore the simulations below to see how these foundational data structures behave.
Interactive Array Simulation
Click the buttons to see array operations. For O(n) operations, affected elements will highlight before they shift.
Interactive Linked List Simulation
Click the buttons below to see linked list operations in action and their time complexities.
List is empty