Python Data Structures 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] | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
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
appendorpop, 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
- 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+?
- 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.
- 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.
- 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.
- About tuples: note the difference between
a = ('A')anda = ('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.def append_to_list(value, my_list=[]): my_list.append(value) return my_listprint(append_to_list(1)) # [1]print(append_to_list(2)) # [1, 2] - unexpected behavior
API Cheat Sheet
List API
# Createmy_list = [] # empty listmy_list = [1, 2, 3] # list with initial valuesmy_list = list("abc") # Create from Iterable : ['a', 'b', 'c']# Access and modifyitem = my_list[0] # index accessmy_list[1] = 10 # modify an elementsubset = my_list[1:3] # slicing: get a sublistsubset = my_list[1:] # slicing: from a position to the endsubset = my_list[:2] # slicing: from the start to a positionall_elements = my_list[:] # slicing: get all elementslast_element = my_list[-1] # negative index: get the last element# Common methodsmy_list.append(4) # append to the endmy_list.insert(1, 5) # insert at a positionmy_list.extend([5, 6]) # extend the listmy_list.pop() # remove and return the last elementmy_list.pop(1) # remove and return the element at a positionmy_list.remove(3) # remove the first element equal to 3my_list.sort() # sort (in place)my_list.reverse() # reverse (in place)len(my_list) # get length3 in my_list # membership testmy_list.count(2) # count occurrencesmy_list.index(3) # find an element's positionTuple API
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 元组的实现原理 (in Chinese).
# Createmy_tuple = () # empty tuplemy_tuple = (1, 2, 3) # tuple with initial values; parentheses optionalmy_tuple = tuple([1, 2, 3]) # Create from Iterable# Accessitem = my_tuple[0] # index accesssubset = my_tuple[1:3] # slicing# Common methodslen(my_tuple) # length3 in my_tuple # membership testmy_tuple.count(2) # count occurrencesmy_tuple.index(3) # find an element's positionSet API
# Createmy_set = set() # empty setmy_set = {1, 2, 3} # set with initial valuesmy_set = set([1, 2, 2, 3]) # Create from Iterable (deduplicates automatically)# Modifymy_set.add(4) # add a single elementmy_set.update([4, 5]) # add multiple elementsmy_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 elementmy_set.clear() # empty the setlen(my_set) # length3 in my_set # membership test (O(1))# Set operationsset1 = {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 relationshipsis_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 testis_subset = set1 <= set2 # subset testis_superset = set1 >= set2 # superset testis_disjoint = set1.isdisjoint(set2) # disjoint testDict API
# Createmy_dict = {} # empty dictmy_dict = {"a": 1, "b": 2} # dict with initial valuesmy_dict = dict(a=1, b=2) # create via keyword argumentsmy_dict = dict([("a", 1), ("b", 2)]) # create from a list of key-value pairs# Access and modifyvalue = 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 pairmy_dict.update({"d": 4, "e": 5}) # add or update key-value pairs in bulk# Deletedel my_dict["a"] # delete a key-value pairvalue = my_dict.pop("b") # delete and return the valueitem = my_dict.popitem() # delete and return the most recently added pair# Common methodskeys = my_dict.keys() # get all keysvalues = my_dict.values() # get all valuesitems = my_dict.items() # get all key-value pairslen(my_dict) # dict length"a" in my_dict # key existence testmy_dict.clear() # empty the dictQueue API
from collections import dequefrom queue import Queue# Using dequeq = deque() # double-ended queueq.append(1) # append on the rightq.appendleft(0) # append on the leftitem = q.pop() # remove from the rightitem = q.popleft() # remove from the left (queue usage)# Using Queue (thread-safe)q = Queue(maxsize=10) # create a queue, optionally with max capacityq.put(1) # add an elementitem = q.get() # get an elementq.task_done() # signal that a task is doneq.join() # block until all elements are processedq.qsize() # current sizeq.empty() # is it emptyq.full() # is it fullStack API
# In Python, stacks are usually implemented with a liststack = [] # empty stackstack.append(1) # pushstack.append(2) # pushitem = stack.pop() # poppeek = stack[-1] # peek at the top (without removing)is_empty = len(stack) == 0 # check if empty# collections.deque also worksfrom collections import dequestack = deque()stack.append(1) # pushitem = stack.pop() # popTricks
# Deduplicate a listnumbers_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 usersunique_to_a = users_a - users_b # users only in ASlicing: syntax
sequence[start:end: step], interval ↩︎

