
Image by Editor | Midjourney
Data structures store and organize data effectively. In Python, different data structures let us access and manage data. Using the right data structure can make programs run faster and use less memory.
This article explains some of the most efficient data structures in Python with simple examples.
List
A list is a dynamic array that stores items in order. It can have repeated values and different data types. Lists are mutable, so you can change, add, or remove elements. Use square brackets [] or the list() constructor to create a list. Access elements using an index, starting from 0 for the first and -1 for the last.
# Creating a list
my_list = [10, 20, 30, 40]
# Modifying the list
my_list.append(50) # Adding an element
my_list.remove(20) # Removing an element
# Accessing elements
first_element = my_list[0]
last_element = my_list[-1]
print("List:", my_list)
print("First Element:", first_element)
print("Last Element:", last_element)
Output:
List: [10, 30, 40, 50] First Element: 10 Last Element: 50
Tuple
A tuple is an immutable sequence that operates faster and consumes less memory than a list. Create a tuple using parentheses () or the tuple() constructor. Access elements using their index, just like lists. However, since tuples are immutable, you cannot modify their elements after creation. This immutability not only leads to performance improvements but also makes tuples suitable for use as keys in dictionaries.
# Creating a tuple
my_tuple = (10, 20, 30, 40)
# Accessing elements
first_element = my_tuple[0]
last_element = my_tuple[-1]
print("Tuple:", my_tuple)
print("First Element:", first_element)
print("Last Element:", last_element)
Output:
Tuple: (10, 20, 30, 40) First Element: 10 Last Element: 40
Dictionary
A dictionary stores key-value pairs and provides fast lookups. It uses a hash table for efficient access. Create a dictionary using curly braces {} with key-value pairs or the dict() constructor. Access values using their unique keys. You can also add, update, or delete key-value pairs dynamically. For safer access, consider using the .get() method and dictionary comprehensions for concise dictionary creation.
# Creating a dictionary
my_dict = {"a": 1, "b": 2, "c": 3}
# Modifying the dictionary
my_dict["d"] = 4 # Adding a new key-value pair
my_dict["b"] = 20 # Updating an existing value
del my_dict["c"] # Removing a key-value pair
# Accessing values
value_a = my_dict["a"]
print("Dictionary:", my_dict)
print("Value of 'a':", value_a)
Output:
Dictionary: {'a': 1, 'b': 20, 'd': 4}
Value of 'a': 1
Set
A set stores unique elements and performs fast membership checks. Create a set using curly braces {} or the set() constructor. Unlike lists and tuples, sets do not support indexing. Instead, you can check for membership using the in operator and perform set operations like union, intersection, and difference. As an alternative to remove(), consider using discard() to avoid errors if the element is not found.
# Creating a set
my_set = {10, 20, 30, 40, 40} # Duplicate 40 is removed automatically
# Modifying the set
my_set.add(50) # Adding an element
my_set.remove(30) # Removing an element
# Checking membership
is_present = 20 in my_set
print("Set:", my_set)
print("Is 20 present?", is_present)
Output:
Set: {40, 10, 50, 20}
Is 20 present? True
Deque
A deque (double-ended queue) lets you quickly add or remove items from both ends. Use the collections.deque() class to create one. It supports indexing like a list but is more efficient for inserting and deleting at the front or back.
from collections import deque
# Creating a deque
my_deque = deque([10, 20, 30, 40])
# Modifying the deque
my_deque.append(50) # Adding to the right
my_deque.appendleft(5) # Adding to the left
my_deque.pop() # Removing from the right
my_deque.popleft() # Removing from the left
print("Deque:", my_deque)
Output:
Deque: deque([10, 20, 30, 40])
Heap
A heap is a special tree-based structure. It works as a priority queue. Use the heapq module to create one. It gives a min-heap by default. The smallest element is always at the root (index 0). Heaps help in quickly finding the smallest or largest element.
import heapq
# Creating a heap
my_heap = [40, 10, 30, 20]
heapq.heapify(my_heap) # Convert list into a min-heap
# Modifying the heap
heapq.heappush(my_heap, 5) # Adding an element
smallest = heapq.heappop(my_heap) # Removing and returning the smallest element
print("Heap:", my_heap)
print("Smallest Element Removed:", smallest)
Note: To implement a max-heap, you can negate the values before pushing them into the heap and negate them again when retrieving.
Output:
Heap: [10, 20, 30, 40] Smallest Element Removed: 5
Conclusion
Choosing the right data structure makes your code faster and more efficient. Lists and tuples store ordered data, but tuples are immutable. Dictionaries enable quick lookups with key-value pairs. Sets store unique items and check membership quickly. Deques help in fast insertions and deletions from both ends. Heaps are useful for managing priority queues. Understanding these structures helps you write better Python programs. Check out additional Python content on Statology to learn more.
