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.
| Method | Syntax | Description |
|---|---|---|
| List | my_list = [1, 2, 3] | Ordered, mutable, indexable sequence of arbitrary elements. |
| Dictionary | my_dict = {"key": "val"} | Key-value mapping. Keys must be unique and hashable (immutable). |
| Set | my_set = {1, 2, 3} | Unordered collection of unique, hashable items. |
| Tuple | my_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.
| Method | Syntax | Description |
|---|---|---|
| deque | from collections import deque | Double-ended queue. Supports fast O(1) appends and pops from both ends. |
| defaultdict | from collections import defaultdict | Dictionary subclass that calls a factory function to supply missing values. |
| Counter | from collections import Counter | Dictionary subclass for counting hashable objects. |
| namedtuple | from collections import namedtuple | Factory function for creating tuple subclasses with named fields. |
| OrderedDict | from collections import OrderedDict | Dictionary 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.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Check Data Type in Python
Learn how to check data types in Python. Understand when to use type() vs isinstance(), handle custom classes, and write safe type check validations.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.