Docsity

Complete Python Cheat Sheet, Cheat Sheet of Programming Languages

Toggle sidebar
bg1
Python Cheat Sheet
Quick reference for Python 3.10+ syntax, built-in data structures, and common idioms.
Basics
x = 10 # int
pi = 3.14 # float
name = "Ada" # str
ok = True # bool
nothing = None # NoneType
print(f"{name} is {x} years old") # f-string
print(f"{pi:.2f}") # 3.14
type(x); isinstance(x, int)
a, b = 1, 2 # multiple assignment
a, b = b, a # swap
Operators
Operator
Meaning
+ - * /
add, subtract, multiply, true divide
//
floor division
%
modulo
**
power
== != < > <= >=
comparison
and or not
logical
in , not in
membership
is , is not
identity
Python Cheat Sheet
Page 1 of 8
pf3
pf4
pf5
pf8

Partial preview of the text

Download Complete Python Cheat Sheet and more Cheat Sheet Programming Languages in PDF only on Docsity!

Python Cheat Sheet

Quick reference for Python 3.10+ syntax, built-in data structures, and common idioms.

Basics

x = 10 # int pi = 3.14 # float name = "Ada" # str ok = True # bool nothing = None # NoneType

print(f"{name} is {x} years old") # f-string print(f"{pi:.2f}") # 3. type(x); isinstance(x, int)

a, b = 1, 2 # multiple assignment a, b = b, a # swap

Operators

Operator Meaning

+ - * / add, subtract, multiply, true divide

// floor division

% modulo

** power

== != < > <= >= comparison

and or not logical

in ,^ not in membership

is , is not identity

Strings

s = "Hello, World" s.lower(); s.upper(); s.title() s.strip(); s.lstrip(); s.rstrip() s.split(",") # ['Hello', ' World'] ", ".join(["a", "b"]) # 'a, b' s.replace("World", "Python") s.startswith("He"); s.endswith("ld") s.find("o") # index or - s[0]; s[-1]; s[0:5]; s[::-1] # indexing, slicing, reverse

Lists

nums = [3, 1, 2] nums.append(4) # add to end nums.insert(0, 9) # insert at index nums.extend([5, 6]) nums.remove(1) # remove first matching value last = nums.pop() # remove and return last nums.sort(reverse=True) # in place sorted(nums) # returns new list len(nums); sum(nums); max(nums); min(nums) nums[1:3]; nums[::2]

Tuples & Sets

t = (1, 2, 3) # immutable x, y, z = t # unpacking

s = {1, 2, 3} # unique, unordered s.add(4); s.discard(2) a | b; a & b; a - b; a ^ b # union, intersection, difference, symmetric diff

Match Statement (3.10+)

match command: case "start": ... case ["go", direction]: ... case {"type": "click", "x": x}: ... case _: ...

Functions

def greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}!"

def total(*args, **kwargs): # variable positional / keyword args return sum(args)

square = lambda x: x * x

def f(a, /, b, *, c): # a positional-only, c keyword-only ...

Avoid mutable default arguments ( def f(x=[]) ); use None and create the list inside.

Comprehensions

squares = [x2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] lookup = {name: len(name) for name in names} unique = {x % 3 for x in range(10)} gen = (x2 for x in range(10)) # lazy generator

Useful Built-ins

map(str, [1, 2, 3]); filter(None, items) any(x > 5 for x in nums); all(x > 0 for x in nums) sorted(items, key=lambda i: i["age"], reverse=True) reversed(items); abs(-3); round(3.14159, 2); divmod(7, 2) min(items, key=len)

Classes & Dataclasses

class Animal: def init(self, name): self.name = name

def speak(self): return f"{self.name} makes a sound"

def repr(self): return f"Animal({self.name!r})"

class Dog(Animal): def speak(self): return f"{self.name} barks"

from dataclasses import dataclass

@dataclass class Point: x: float y: float = 0.

Modules & Standard Library

import os, sys, math, random from datetime import datetime, timedelta from collections import Counter, defaultdict, deque from itertools import chain, groupby, combinations from functools import lru_cache, reduce

Counter("banana").most_common(2) now = datetime.now().strftime("%Y-%m-%d %H:%M")

Decorators & Generators

import functools

def timer(func): @functools.wraps(func) def wrapper(*args, *kwargs): import time start = time.perf_counter() result = func(args, **kwargs) print(f"{func.name}: {time.perf_counter() - start:.3f}s") return result return wrapper

@timer def work(): ...

def countdown(n): # generator while n > 0: yield n n -= 1

Async Basics

import asyncio

async def fetch(n): await asyncio.sleep(1) return n

async def main(): results = await asyncio.gather(fetch(1), fetch(2), fetch(3)) print(results)

asyncio.run(main())

Virtual Environments & pip

python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install requests pandas pip freeze > requirements.txt pip install -r requirements.txt deactivate

Common Pitfalls

Mutable default arguments shared between calls.

Using is to compare values instead of == (reserve is for None ).

Modifying a list while iterating over it.

Forgetting that / always returns a float; use // for integer division.

Catching bare except: ; catch specific exceptions instead.