Programming · Cheatsheet
Python Essentials Cheatsheet
Python syntax, data structures, comprehensions, built-in functions, and common patterns
59 commands 8 sections
No entry matches that filter.
-
x = 10Integer -
x = 3.14Float -
x = "hello"String -
x = True / FalseBoolean -
x = NoneNoneType (null equivalent) -
type(x)Get type of variable -
isinstance(x, int)Check if instance of type -
int() float() str() bool()Type conversion functions
-
f"Hello {name}"f-string (formatted string literal) -
s.upper() / s.lower()Convert case -
s.strip()Remove leading/trailing whitespace -
s.split(",") / ",".join(lst)Split string / join list -
s.replace("old", "new")Replace substring -
s.startswith() / s.endswith()Check prefix/suffix -
s.find("sub")Find substring index (-1 if not found) -
s[1:5]Slice string (index 1 to 4) -
s[::-1]Reverse string
-
lst = [1, 2, 3]Create list -
lst.append(4)Add element to end -
lst.insert(0, "first")Insert at index -
lst.pop() / lst.pop(0)Remove last / at index -
lst.remove(val)Remove first occurrence of value -
lst.sort() / sorted(lst)Sort in-place / return sorted copy -
lst.reverse()Reverse in-place -
len(lst)Number of elements -
val in lstCheck if value exists -
[x*2 for x in lst]List comprehension -
[x for x in lst if x > 0]Filtered list comprehension
-
d = {"key": "val"}Create dictionary -
d["key"] / d.get("key", default)Access value / with default -
d.keys() / d.values() / d.items()Get keys / values / pairs -
d.update(other)Merge another dict into d -
d.pop("key")Remove and return value -
"key" in dCheck if key exists -
{k: v for k, v in items}Dict comprehension -
d | otherMerge dicts (Python 3.9+)
-
if x > 0: ... elif: ... else:Conditional -
for item in iterable:For loop -
for i, val in enumerate(lst):Loop with index -
for k, v in d.items():Loop over dict items -
while condition:While loop -
break / continue / passLoop control -
x if condition else yTernary expression -
match value: case pattern:Structural pattern matching (3.10+)
-
def fn(a, b="default"):Function with default parameter -
def fn(*args, **kwargs):Variable arguments -
lambda x: x * 2Anonymous function -
map(fn, iterable)Apply function to each element -
filter(fn, iterable)Filter elements by function -
@decoratorFunction decorator syntax -
def fn() -> int:Type hint for return value
-
with open("f.txt") as f:Open file (auto-close) -
f.read() / f.readlines()Read entire file / as lines -
f.write("text")Write to file -
try: ... except Exception as e:Try/except block -
try: ... finally:Always-run cleanup block -
raise ValueError("msg")Raise an exception
-
https://docs.python.org/3/reference/Python 3 language reference: syntax and execution rules. -
https://docs.python.org/3/library/Python 3 standard library: built-in types, functions, and file operations.