PYTHON

Python Data Structures: Syntax, Usage, and Examples

Python data structures are essential for organizing, storing, and manipulating data efficiently. They help programmers manage collections of data and perform operations such as searching, sorting, and modifying data. Python provides built-in data structures like lists, tuples, sets, and dictionaries, as well as more advanced structures like trees and graphs. Understanding these structures and when to use them is crucial for writing efficient and readable code.


How to Use Data Structures in Python

Python has several built-in data structures, each optimized for different use cases. The four most commonly used ones are:

  • Lists: Ordered, mutable collections that allow duplicates
  • Tuples: Ordered, immutable collections
  • Sets: Unordered collections with unique elements
  • Dictionaries: Key-value pairs for fast lookups

Lists in Python

A list is an ordered collection that allows adding, removing, and modifying elements. Lists support indexing and slicing, making them easy to manipulate.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple

# Modifying a list
fruits.append("orange")  # Adds an item
fruits.remove("banana")  # Removes an item
print(fruits)  # Output: ['apple', 'cherry', 'orange']

Tuples in Python

Tuples are similar to lists but immutable, meaning their values cannot be changed after creation.

coordinates = (10, 20)
print(coordinates[0])  # Output: 10

Sets in Python

A set is an unordered collection of unique elements. It is useful for removing duplicates and performing mathematical set operations.

numbers = {1, 2, 3, 3, 4}
print(numbers)  # Output: {1, 2, 3, 4}

# Adding elements to a set
numbers.add(5)
print(numbers)  # Output: {1, 2, 3, 4, 5}

Dictionaries in Python

Dictionaries store key-value pairs and allow for quick lookups and modifications.

person = {"name": "Alice", "age": 30}
print(person["name"])  # Output: Alice

# Adding a new key-value pair
person["city"] = "New York"
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

When to Use Data Structures in Python

Different data structures are useful in different scenarios. Choosing the right one depends on how data needs to be accessed and manipulated.

Lists

Use lists when you need:

  • Ordered data storage
  • Dynamic resizing (adding/removing elements)
  • Support for duplicate values

Example: Storing a list of tasks in a to-do application.

tasks = ["Buy groceries", "Finish project", "Call mom"]                       

Tuples

Use tuples when:

  • Data should remain unchanged (e.g., coordinates, days of the week)
  • Memory efficiency is important

Example: Storing constant data like RGB color values.

color = (255, 0, 0)  # Red color in RGB format

Sets

Use sets when:

  • You need unique elements (e.g., filtering duplicate email addresses)
  • Mathematical set operations like unions and intersections are required

Example: Finding common friends between two social media users.

friends_a = {"Alice", "Bob", "Charlie"}
friends_b = {"Charlie", "David", "Eve"}
common_friends = friends_a & friends_b  # Output: {'Charlie'}

Dictionaries

Use dictionaries when:

  • You need to store key-value pairs for fast lookups
  • You require fast updates and retrievals

Example: Storing product details in an e-commerce application.

product = {"name": "Laptop", "price": 999, "stock": 5}
print(product["price"])  # Output: 999

Examples of Data Structures in Python

Using a Dictionary for Fast Lookups

Dictionaries are optimized for key-based searches, making them ideal for scenarios where data retrieval needs to be fast.

employee_salaries = {"Alice": 50000, "Bob": 60000, "Charlie": 70000}
print(employee_salaries.get("Bob"))  # Output: 60000

Set Operations

Sets are useful for handling unique elements and performing operations like unions and intersections.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union_set = set1 | set2  # {1, 2, 3, 4, 5, 6}
intersection_set = set1 & set2  # {3, 4}

Implementing a Tree Data Structure

Trees store data hierarchically and are commonly used in searching and sorting. A binary search tree (BST) is a simple example.

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def insert(root, value):
    if root is None:
        return Node(value)
    if value < root.value:
        root.left = insert(root.left, value)
    else:
        root.right = insert(root.right, value)
    return root

root = insert(None, 10)
insert(root, 5)
insert(root, 15)

Learn More About Data Structures in Python

Python Data Structures and Algorithms

Understanding data structures is crucial for writing optimized code. Many algorithms, such as sorting and searching, rely on efficient data storage and retrieval.

What Are Data Structures in Python?

Data structures define how data is organized and accessed. Python provides built-in structures like lists and dictionaries, while custom structures like trees and graphs allow for more specialized use cases.

Trees in Data Structures

Trees are hierarchical structures used in databases, file systems, and search algorithms. Binary trees, heaps, and B-trees are some common tree structures.

Python data structures provide powerful tools for managing data efficiently. Choosing the right one ensures optimal performance and scalability in your programs.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH