Python Collections & Data Structures Cheat Sheet

Complete guide to Python collections module and native data structures. Learn lists, dicts, sets, tuples, deques, and namedtuples.

Native Built-in Types

Standard container classes natively available without additional imports.

MethodSyntaxDescription
Listmy_list = [1, 2, 3]Ordered, mutable, indexable sequence of arbitrary elements.
Dictionarymy_dict = {"key": "val"}Key-value mapping. Keys must be unique and hashable (immutable).
Setmy_set = {1, 2, 3}Unordered collection of unique, hashable items.
Tuplemy_tuple = (1, 2, 3)Ordered, immutable sequence. Often used for record data types.

Specialized Collections Module Structures

Structures imported from collections for specific performance features.

MethodSyntaxDescription
dequefrom collections import dequeDouble-ended queue. Supports fast O(1) appends and pops from both ends.
defaultdictfrom collections import defaultdictDictionary subclass that calls a factory function to supply missing values.
Counterfrom collections import CounterDictionary subclass for counting hashable objects.
namedtuplefrom collections import namedtupleFactory function for creating tuple subclasses with named fields.
OrderedDictfrom collections import OrderedDictDictionary subclass that remembers key insertion order.

Frequently Asked Questions

When should I use deque instead of a list?

Use deque (double-ended queue) when you need fast O(1) appends and pops from both ends. Lists have O(n) complexity for inserting/removing at the front.

How does defaultdict work?

defaultdict automatically creates a default value (e.g., list, int) if you attempt to access a key that does not exist, preventing KeyErrors.

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.