File Operations
# Read entire file
content = open("file.txt").read()
# Read lines
lines = open("file.txt").readlines()
# Write to file
open("out.txt", "w").write("hello")
# Read JSON
import json; data = json.load(open("data.json"))
Data Processing
# Flatten nested list
flat = [x for sub in nested for x in sub]
# Count occurrences
from collections import Counter; Counter("hello")
# Most common
Counter(words).most_common(10)
# Remove duplicates keeping order
list(dict.fromkeys(items))
# Transpose matrix
list(zip(*matrix))
# Chunk list
[lst[i:i+n] for i in range(0, len(lst), n)]
String Operations
# Reverse string
"hello"[::-1]
# Check palindrome
s == s[::-1]
# Title case
"hello world".title()
# Remove whitespace
" hi ".strip()
# Join list to string
", ".join(["a", "b", "c"])
HTTP & Web
# Simple HTTP GET
import urllib.request; urllib.request.urlopen("https://...").read()
# HTTP server in one line (terminal)
# python -m http.server 8000
# URL encode
from urllib.parse import quote; quote("hello world")
Math & Logic
# Swap variables
a, b = b, a
# Conditional expression
x = "yes" if condition else "no"
# Fibonacci
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
# Check if all/any
all(x > 0 for x in nums)
any(x < 0 for x in nums)