Published on

Python Cheatsheet for Intermediate to Advanced Users

Authors
  • avatar
    Name
    Winston Brown
    Twitter

Python Cheatsheet: Essential Shortcuts & Core Concepts for Intermediate to Advanced Users

Download the PDF Version

Python is powerful and efficient for development, and knowing some handy shortcuts can make coding even more streamlined. This cheatsheet covers essential Python techniques, from list comprehensions to powerful standard library functions.

Shortcut / ConceptDescriptionExample
List ComprehensionsCreate lists in one line, filtering or modifying elements.[x**2 for x in range(10) if x % 2 == 0]
Dictionary ComprehensionsGenerate dictionaries on the fly with custom keys and values.{x: x**2 for x in range(5)}
Lambda FunctionsWrite small anonymous functions inline, useful for quick operations.sorted(data, key=lambda x: x['age'])
F-stringsEmbed expressions directly in strings for clean, efficient formatting.name = "Winston"; f"Hello, {name}!"
EnumerateGet index and value from an iterable in a loop.for i, value in enumerate(lst): print(i, value)
ZipCombine multiple lists into tuples, iterating over each element.list(zip(list1, list2))
UnpackingUnpack elements from lists, tuples, and dictionaries into variables easily.a, b, c = my_tuple
***args & kwargsAllow functions to take an arbitrary number of arguments and keyword arguments.def func(*args, **kwargs):
Ternary OperatorWrite simple conditional expressions in one line."even" if x % 2 == 0 else "odd"
GeneratorsUse yield to create memory-efficient generators instead of full lists.def gen(): yield x
Map, Filter, ReduceFunctional programming tools for element-wise mapping, filtering, or reducing a sequence.map(func, iterable)
Context ManagersManage resources using with statements (e.g., file handling).with open("file.txt") as f:
Named TuplesCreate lightweight, readable, and immutable tuple-like objects.from collections import namedtuple; Point = namedtuple('Point', 'x y')
CounterCount elements in a list or other iterable with ease.from collections import Counter; Counter(lst)
DefaultdictUse dictionaries with default values for missing keys.from collections import defaultdict; d = defaultdict(int)
Datetime ManipulationWork with dates and times effectively.from datetime import datetime; now = datetime.now()
PathlibModern and efficient way to work with paths and file systems.from pathlib import Path; Path("myfile.txt").exists()
List FlatteningQuickly flatten nested lists with itertools.from itertools import chain; list(chain(*nested_list))
Dealing with JSONParse JSON objects easily from strings or files.import json; data = json.loads(json_str)
Exception Handling with elseUse else in try-except blocks to run code only if no exception occurred.try: ... except: ... else: ...
Type HintingAnnotate code with type hints for readability and IDE support.def func(x: int) -> int:

Let me know what you think about this list in the comments! 🙏