Essential code snippets and shortcuts for Python, Java, C++, C, JavaScript, TypeScript, Go, Rust, Kotlin, Swift, PHP, R, Scala, Julia, Dart, PowerShell, Bash, Terraform, YAML, HTML, CSS & SQL
# Basic list comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Conditional list comprehension
words = ["hello", "world", "python", "code"]
long_words = [word.upper() for word in words if len(word) > 4]
print(long_words) # ['HELLO', 'WORLD', 'PYTHON']# Basic dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
# Filter dictionary
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v > 2}
print(filtered) # {'c': 3, 'd': 4}set1 & set2 # intersection
set1 | set2 # union
set1 - set2 # difference
set1 ^ set2 # symmetric differencelambda x: x**2
sorted(data, key=lambda x: x[1])
filter(lambda x: x > 0, numbers)
map(lambda x: x*2, numbers)from collections import Counter, defaultdict, deque
Counter("hello") # {'l': 2, 'h': 1, 'e': 1, 'o': 1}
defaultdict(list) # auto-creates missing keys
deque([1,2,3]) # double-ended queuefrom itertools import permutations, combinations, product
list(permutations([1,2,3], 2)) # [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]
list(combinations([1,2,3], 2)) # [(1,2), (1,3), (2,3)]
list(product([1,2], repeat=2)) # [(1,1), (1,2), (2,1), (2,2)]s.strip() # remove whitespace
s.split(",") # split by comma
",".join(list) # join with comma
s.replace("old", "new") # replace substring
s.find("sub") # find index (-1 if not found)name = "Alice"
age = 25
f"Hello {name}, you are {age} years old"
f"Value: {value:.2f}" # format to 2 decimals
f"Binary: {num:08b}" # 8-digit binaryimport re
re.search(r"\d+", "abc123def") # find digits
re.findall(r"\w+", text) # find all words
re.sub(r"\d+", "X", text) # replace digits with X
re.match(r"^\w+@\w+\.\w+$", email) # email validations[::-1] # reverse string
s[::2] # every 2nd character
s[1:-1] # remove first and last
s.startswith("prefix")
s.endswith("suffix")
s.isdigit(), s.isalpha(), s.isalnum()def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1# DFS (Depth-First Search)
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited
# BFS (Breadth-First Search)
from collections import deque
def bfs(graph, start):
visited = set([start])
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return visited# Built-in sorting
sorted([3,1,4,1,5]) # returns new list
list.sort() # in-place sorting
sorted(data, key=lambda x: x[1]) # sort by second element
sorted(data, reverse=True) # descending order
# Custom sorting
from functools import cmp_to_key
def compare(a, b):
return a - b
sorted(data, key=cmp_to_key(compare))# Memoization with decorator
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Manual memoization
def fib_memo(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
return memo[n]class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self._private = "hidden" # convention for private
def __str__(self):
return f"Person({self.name}, {self.age})"
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
@property
def adult(self):
return self.age >= 18
@staticmethod
def from_string(person_str):
name, age = person_str.split('-')
return Person(name, int(age))class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # call parent constructor
self.breed = breed
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"# Function decorator
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
# Class decorator
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instancedef mystery():
x = []
for i in range(3):
x.append(lambda: i)
return x
funcs = mystery()
for f in funcs:
print(f())def append_to(num, target=[]):
target.append(num)
return target
print(append_to(12))
print(append_to(42))a = [1, 2, 3]
b = a
c = a[:]
a.append(4)
print("a:", a)
print("b:", b)
print("c:", c)x = 5
def outer():
x = 10
def inner():
nonlocal x
x += 1
return x
return inner
func = outer()
print(func())
print(func())
print(x)class Counter:
count = 0
def __init__(self):
Counter.count += 1
self.instance_count = Counter.count
c1 = Counter()
c2 = Counter()
c3 = Counter()
print(f"c1: {c1.instance_count}, class: {Counter.count}")
print(f"c2: {c2.instance_count}, class: {Counter.count}")
print(f"c3: {c3.instance_count}, class: {Counter.count}")# WRONG - Mutable default argument
def add_item(item, target_list=[]):
target_list.append(item)
return target_list
list1 = add_item("a") # ["a"]
list2 = add_item("b") # ["a", "b"] - UNEXPECTED!
# CORRECT - Use None as default
def add_item(item, target_list=None):
if target_list is None:
target_list = []
target_list.append(item)
return target_list
# Alternative - Use copy
def add_item(item, target_list=None):
target_list = target_list or []
target_list = target_list.copy() # Don't modify original
target_list.append(item)
return target_list# WRONG - Late binding closure
functions = []
for i in range(3):
functions.append(lambda: i) # All will return 2!
for f in functions:
print(f()) # Prints: 2, 2, 2
# CORRECT - Early binding with default argument
functions = []
for i in range(3):
functions.append(lambda x=i: x)
for f in functions:
print(f()) # Prints: 0, 1, 2
# CORRECT - Using functools.partial
from functools import partial
def print_num(x):
return x
functions = [partial(print_num, i) for i in range(3)]# WRONG - Using is for value comparison
a = 256
b = 256
print(a is b) # True (small integers are cached)
a = 257
b = 257
print(a is b) # False (larger integers are not cached)
# WRONG - Using == for identity
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True (same content)
print(list1 is list2) # False (different objects)
# CORRECT usage
# Use == for value comparison
if name == "John":
print("Hello John")
# Use is for identity comparison (None, True, False)
if value is None:
print("No value provided")
if flag is True: # Better: if flag:
print("Flag is set")# WRONG - UnboundLocalError
count = 0
def increment():
count += 1 # UnboundLocalError!
return count
# CORRECT - Use global keyword
count = 0
def increment():
global count
count += 1
return count
# WRONG - Modifying list during iteration
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Skips elements!
# CORRECT - Iterate over copy or use list comprehension
numbers = [1, 2, 3, 4, 5]
for num in numbers.copy():
if num % 2 == 0:
numbers.remove(num)
# Better - Use list comprehension
numbers = [num for num in numbers if num % 2 != 0]# Reading files
with open("file.txt", "r") as f:
content = f.read() # read entire file
lines = f.readlines() # read all lines
for line in f: # iterate line by line
print(line.strip())
# Writing files
with open("output.txt", "w") as f:
f.write("Hello World\n")
f.writelines(["line1\n", "line2\n"])
# JSON handling
import json
with open("data.json", "r") as f:
data = json.load(f)
with open("output.json", "w") as f:
json.dump(data, f, indent=2)try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (ValueError, TypeError) as e:
print(f"Value/Type error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No exceptions occurred")
finally:
print("This always executes")
# Custom exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
raise CustomError("Something went wrong")