Programming57 entries

Python Essentials

Python syntax, data structures, comprehensions, built-in functions, and common patterns

1Data Types & Variables

x = 10
Integer
x = 3.14
Float
x = "hello"
String
x = True / False
Boolean
x = None
NoneType (null equivalent)
type(x)
Get type of variable
isinstance(x, int)
Check if instance of type
int() float() str() bool()
Type conversion functions

2Strings

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

3Lists

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 lst
Check if value exists
[x*2 for x in lst]
List comprehension
[x for x in lst if x > 0]
Filtered list comprehension

4Dictionaries

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 d
Check if key exists
{k: v for k, v in items}
Dict comprehension
d | other
Merge dicts (Python 3.9+)

5Control Flow

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 / pass
Loop control
x if condition else y
Ternary expression
match value: case pattern:
Structural pattern matching (3.10+)

6Functions

def fn(a, b="default"):
Function with default parameter
def fn(*args, **kwargs):
Variable arguments
lambda x: x * 2
Anonymous function
map(fn, iterable)
Apply function to each element
filter(fn, iterable)
Filter elements by function
@decorator
Function decorator syntax
def fn() -> int:
Type hint for return value

7File I/O & Error Handling

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