Python Data Structures Guide

A comprehensive guide to Python’s built-in data structures.

Lists

Lists are mutable sequences in Python:

1
2
3
4
5
6
7
8
9
10
11
12
# Creating lists
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]

# List operations
fruits.append('orange')
fruits.extend(['grape', 'mango'])
first_fruit = fruits[0]
last_fruit = fruits[-1]

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

Dictionaries

Dictionaries store key-value pairs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Creating dictionaries
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}

# Accessing values
name = person['name']
age = person.get('age', 0)

# Dictionary methods
keys = person.keys()
values = person.values()
items = person.items()

Sets

Sets are unordered collections of unique elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Creating sets
colors = {'red', 'green', 'blue'}
numbers = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}

# Set operations
colors.add('yellow')
colors.remove('red')
is_member = 'blue' in colors

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2

Tuples

Tuples are immutable sequences:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Creating tuples
coordinates = (10, 20)
rgb = (255, 128, 0)

# Tuple unpacking
x, y = coordinates
r, g, b = rgb

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

These data structures form the foundation of Python programming!