Skip to main content

Python Data Structures Guide

Master Python data structures for efficient programming.

Cover image for: Python Data Structures Guide

Python Data Structures Guide

Learn Python data structures inside out.

Lists

Ordered, mutable sequences:

fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
fruits[0] = 'pear'  # Mutable

# List comprehension
squares = [x**2 for x in range(10)]

Dictionaries

Key-value pairs:

user = {
    'name': 'John',
    'age': 30,
    'city': 'NYC'
}

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}

Sets

Unordered collections of unique elements:

numbers = {1, 2, 3, 4, 5}
numbers.add(6)
numbers.add(1)  # No duplicate

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)  # Union: {1, 2, 3, 4, 5}
print(a & b)  # Intersection: {3}

Tuples

Immutable sequences:

point = (10, 20)
x, y = point  # Unpacking

# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x)  # 10

Conclusion

Understanding data structures is fundamental to writing efficient Python code.

Share this article :