﻿---
title: Python Data Structures Cheat Sheet
date: 2025-04-02
excerpt: A quick reference for Python data structures and their common operations, from lists and dicts to queues and stacks.
tags:
  - Python
  - Algorithm
cover: https://assets.vluv.space/cover/Lang/Python/AnimeChillPool.webp
updated: 2026-07-08 21:17:39
lang: en
i18n:
  cn: /data_struct
  translation: 2
---

> [!tldr] Cheat Sheet
>
> A simple rundown of common operations on Python data structures, for quick reference later.

## Python Data Structures

### Overview

| Feature      | List | Tuple | Set  | Dict     | Queue     | Stack  |
| ------------ | ---- | ----- | ---- | -------- | --------- | ------ |
| syntax       | `[]` | `()`  | `{}` | `{k: v}` | `Queue()` | `list` |
| Mutability   | ✅    | ❌     | ✅    | ✅        | ✅         | ✅      |
| Ordered      | ✅    | ✅     | ❌    | ✅        | ✅         | ✅      |
| Duplicates   | ✅    | ✅     | ❌    | ❌        | ✅         | ✅      |
| Index access | ✅    | ✅     | ❌    | ❌        | ❌         | ✅      |
| Slicing[^1]  | ✅    | ✅     | ❌    | ❌        | ❌         | ✅      |

> [!Note]
>
> When a mutable object is passed into a function as an argument:
>
>  - **It will be modified** if the function mutates it in place (e.g. a list's `append` or `pop`, updating a dict's key-value pairs).
>  - **It will not be modified** if the function merely reassigns the parameter (pointing it to a new object).
#### Note

1. In CPython 3.6, dictionaries were ordered by implementation detail, but in Python 3.7+ dictionary order was officially made part of the language specification. For more info: [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6)
2. List vs Tuple: While both can store ordered sequences, tuples are immutable and typically used for fixed collections of items that shouldn't change (like coordinates or RGB values). Lists are mutable and better for collections that need to be modified.
3. Set vs List: Sets are optimized for fast membership testing (O(1)) and eliminating duplicates, but don't maintain order. Use sets when uniqueness matters more than order.
4. Dict vs List: Dictionaries provide O(1) lookup by key, making them ideal for key-value mappings. Lists require O(n) for lookups by value.
5. About tuples: note the difference between `a = ('A')` and `a = ('A',)`. The former is a string, the latter a tuple. To create a single-element tuple, you must add a comma after the element.

##### Mutability

- **Mutable**: Lists, Sets, Dicts, Queues, Stacks
- **Immutable**: Tuples

Mutability indicates whether a data structure can be modified after creation. Mutable structures allow in-place modification; immutable ones cannot change once created. This design is mainly about performance and safety. Immutable data structures can't be accidentally modified inside function calls, which makes them safer in multithreaded environments. They can also serve as dict keys or set elements, since their hash values never change.

A common pitfall is passing a mutable object (like a list or dict) as a default function argument. This can lead to unexpected behavior, because default arguments are shared across function calls.

```python
def append_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list
print(append_to_list(1))  # [1]
print(append_to_list(2))  # [1, 2] - unexpected behavior
```

### API Cheat Sheet

#### List API

```python
# Create
my_list = []                      # empty list
my_list = [1, 2, 3]               # list with initial values
my_list = list("abc")             # Create from Iterable : ['a', 'b', 'c']

# Access and modify
item = my_list[0]                 # index access
my_list[1] = 10                   # modify an element
subset = my_list[1:3]             # slicing: get a sublist
subset = my_list[1:]              # slicing: from a position to the end
subset = my_list[:2]              # slicing: from the start to a position
all_elements = my_list[:]         # slicing: get all elements
last_element = my_list[-1]        # negative index: get the last element


# Common methods
my_list.append(4)                 # append to the end
my_list.insert(1, 5)              # insert at a position
my_list.extend([5, 6])            # extend the list
my_list.pop()                     # remove and return the last element
my_list.pop(1)                    # remove and return the element at a position
my_list.remove(3)                 # remove the first element equal to 3
my_list.sort()                    # sort (in place)
my_list.reverse()                 # reverse (in place)
len(my_list)                      # get length
3 in my_list                      # membership test
my_list.count(2)                  # count occurrences
my_list.index(3)                  # find an element's position
```

#### Tuple API

> [!INFO]
>
> Compared to List, Tuple removes the add/remove/modify APIs. It is `hashable`, so it can serve as a dict key or a set element.
> For more on tuples, see [解密 Python 元组的实现原理](https://mp.weixin.qq.com/s/5S3cYjrGg0kxzOUeyA0_Eg) (in Chinese).

```python
# Create
my_tuple = ()                     # empty tuple
my_tuple = (1, 2, 3)              # tuple with initial values; parentheses optional
my_tuple = tuple([1, 2, 3])       # Create from Iterable

# Access
item = my_tuple[0]                # index access
subset = my_tuple[1:3]            # slicing

# Common methods
len(my_tuple)                     # length
3 in my_tuple                     # membership test
my_tuple.count(2)                 # count occurrences
my_tuple.index(3)                 # find an element's position
```

#### Set API

```python
# Create
my_set = set()                    # empty set
my_set = {1, 2, 3}                # set with initial values
my_set = set([1, 2, 2, 3])        # Create from Iterable (deduplicates automatically)

# Modify
my_set.add(4)                     # add a single element
my_set.update([4, 5])             # add multiple elements
my_set.remove(1)                  # remove an element (raises if absent)
my_set.discard(1)                 # remove an element (no error if absent)
my_set.pop()                      # remove and return an arbitrary element
my_set.clear()                    # empty the set

len(my_set)                       # length
3 in my_set                       # membership test (O(1))

# Set operations

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2         # union: {1, 2, 3, 4, 5}
intersection = set1 & set2  # intersection: {3}
difference = set1 - set2    # difference: {1, 2}
sym_diff = set1 ^ set2      # symmetric difference: {1, 2, 4, 5}

# Set relationships
is_subset = set1 <= set2    # subset test, or set1.issubset(set2)
is_superset = set1 >= set2  # superset test, or set1.issuperset(set2)
is_disjoint = set1.isdisjoint(set2)  # disjoint test
is_subset = set1 <= set2    # subset test
is_superset = set1 >= set2  # superset test
is_disjoint = set1.isdisjoint(set2)  # disjoint test
```

#### Dict API

```python
# Create
my_dict = {}                      # empty dict
my_dict = {"a": 1, "b": 2}        # dict with initial values
my_dict = dict(a=1, b=2)          # create via keyword arguments
my_dict = dict([("a", 1), ("b", 2)])  # create from a list of key-value pairs

# Access and modify
value = my_dict["a"]              # key access (raises if key is absent)
value = my_dict.get("c", 0)       # key access (with a default)
my_dict["c"] = 3                  # add or update a key-value pair
my_dict.update({"d": 4, "e": 5})  # add or update key-value pairs in bulk

# Delete
del my_dict["a"]                  # delete a key-value pair
value = my_dict.pop("b")          # delete and return the value
item = my_dict.popitem()          # delete and return the most recently added pair

# Common methods
keys = my_dict.keys()             # get all keys
values = my_dict.values()         # get all values
items = my_dict.items()           # get all key-value pairs
len(my_dict)                      # dict length
"a" in my_dict                    # key existence test
my_dict.clear()                   # empty the dict
```

#### Queue API

```python
from collections import deque
from queue import Queue

# Using deque
q = deque()                       # double-ended queue
q.append(1)                       # append on the right
q.appendleft(0)                   # append on the left
item = q.pop()                    # remove from the right
item = q.popleft()                # remove from the left (queue usage)

# Using Queue (thread-safe)
q = Queue(maxsize=10)             # create a queue, optionally with max capacity
q.put(1)                          # add an element
item = q.get()                    # get an element
q.task_done()                     # signal that a task is done
q.join()                          # block until all elements are processed
q.qsize()                         # current size
q.empty()                         # is it empty
q.full()                          # is it full
```

#### Stack API

```python
# In Python, stacks are usually implemented with a list
stack = []                        # empty stack
stack.append(1)                   # push
stack.append(2)                   # push
item = stack.pop()                # pop
peek = stack[-1]                  # peek at the top (without removing)
is_empty = len(stack) == 0        # check if empty

# collections.deque also works
from collections import deque
stack = deque()
stack.append(1)                   # push
item = stack.pop()                # pop
```

### Tricks

```python
# Deduplicate a list
numbers_list = [1, 2, 2, 3, 3, 3]
unique_numbers = list(set(numbers_list))  # [1, 2, 3]

# Use sets for intersection, union, difference, etc.
users_a = {'Alice', 'Bob', 'Charlie'}
users_b = {'Charlie', 'David', 'Eve'}
common_users = users_a & users_b  # {'Charlie'}
all_users = users_a | users_b     # all users
unique_to_a = users_a - users_b   # users only in A
```

[^1]: Slicing: syntax `sequence[start:end: step]`, interval $[start, end)$
