Comprehensive reference for basic usage
# Variable assignment
x = 10
name = "Alice"
is_active = True
# Multiple assignment
a, b, c = 1, 2, 3
# Swap variables
a, b = b, a
# Type conversion
num_str = "123"
num = int(num_str)
# If-elif-else
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
# Ternary operator
result = "Even" if x % 2 == 0 else "Odd"
# For loop
for i in range(5): # 0 to 4
print(i)
# Iterate through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# With index
for idx, fruit in enumerate(fruits):
print(f"{idx}: {fruit}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop control
for num in range(10):
if num == 3:
continue # Skip this iteration
if num == 7:
break # Exit loop
print(num)
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default arguments
def power(base, exponent=2):
return base ** exponent
# Variable arguments
def sum_all(*args):
return sum(args)
# Keyword arguments
def create_user(**kwargs):
print(kwargs) # Dictionary of arguments
# Lambda functions
square = lambda x: x * x
sorted_names = sorted(names, key=lambda x: x.lower())
def add(a: int, b: int) -> int:
return a + b
# String creation
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = """Multi-line
string"""
# String operations
name = "Alice"
greeting = f"Hello, {name}!" # f-string (Python 3.6+)
length = len(name)
substring = name[1:3] # 'li'
# Common methods
"hello".upper() # 'HELLO'
"HELLO".lower() # 'hello'
" hello ".strip() # 'hello'
"a,b,c".split(',') # ['a', 'b', 'c']
'-'.join(['a', 'b']) # 'a-b'
# String formatting
"{} + {} = {}".format(1, 2, 3) # '1 + 2 = 3'
"%d + %d = %d" % (1, 2, 3) # Old style
# List creation
numbers = [1, 2, 3]
mixed = [1, "two", 3.0]
# List operations
numbers.append(4) # [1, 2, 3, 4]
numbers.insert(1, 1.5) # [1, 1.5, 2, 3, 4]
numbers.remove(2) # [1, 1.5, 3, 4]
popped = numbers.pop() # 4, list is [1, 1.5, 3]
# List comprehensions
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# Slicing
nums = [0, 1, 2, 3, 4]
nums[1:3] # [1, 2]
nums[:3] # [0, 1, 2]
nums[2:] # [2, 3, 4]
nums[::-1] # Reverse list [4, 3, 2, 1, 0]
# Dictionary creation
person = {"name": "Alice", "age": 30}
# Dictionary operations
person["email"] = "alice@example.com" # Add key
age = person.get("age") # Get value
email = person.pop("email") # Remove key
# Dictionary comprehension
squares = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
# Iterating
for key, value in person.items():
print(f"{key}: {value}")
# Tuples (immutable)
point = (10, 20)
x, y = point # Unpacking
# Sets (unique elements)
primes = {2, 3, 5, 7}
primes.add(11) # Add element
evens = {2, 4, 6, 8}
union = primes | evens # {2, 3, 4, 5, 6, 7, 8, 11}
import numpy as np
# Creating arrays
arr1 = np.array([1, 2, 3]) # 1D array
arr2 = np.array([[1, 2], [3, 4]]) # 2D array
zeros = np.zeros((3, 3)) # 3x3 zeros
ones = np.ones((2, 4)) # 2x4 ones
identity = np.eye(3) # 3x3 identity
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
# Array operations
arr = np.array([1, 2, 3])
arr + 1 # [2, 3, 4]
arr * 2 # [2, 4, 6]
np.sqrt(arr) # [1., 1.414, 1.732]
# Indexing and slicing
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix[1, 2] # 6 (second row, third column)
matrix[:, 1] # [2, 5, 8] (second column)
# Useful functions
arr = np.array([3, 1, 4, 2])
arr.sum() # 10
arr.mean() # 2.5
arr.max() # 4
np.sort(arr) # [1, 2, 3, 4]
import matplotlib.pyplot as plt
# Simple line plot
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()
# Scatter plot
plt.scatter(x, y, color='red', marker='o')
plt.show()
# Bar chart
labels = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(labels, values)
plt.show()
# Histogram
data = np.random.normal(0, 1, 1000)
plt.hist(data, bins=30)
plt.show()
# Subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(x, y)
ax2.scatter(x, y)
import pandas as pd
# Series (1D)
s = pd.Series([1, 3, 5, np.nan, 6, 8])
# DataFrame (2D)
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': pd.Timestamp('20230101'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': np.array([3] * 4, dtype='int32'),
'E': ['test', 'train', 'test', 'train'],
'F': 'foo'
})
# Read CSV
data = pd.read_csv('data.csv')
# Basic operations
df.head() # First 5 rows
df.describe() # Summary statistics
df['A'].mean() # Mean of column A
df[df['A'] > 2] # Filtering
# Grouping
df.groupby('E').sum() # Group by column E and sum
# Flatten list of lists
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
# Zip and unzip
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
zipped = list(zip(names, ages)) # [('Alice',25), ('Bob',30)...]
names, ages = zip(*zipped)
# Find most common element
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange']
most_common = Counter(words).most_common(1)
# Dictionary merge (Python 3.5+)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2} # {'a':1, 'b':3, 'c':4}
# Default dictionary
from collections import defaultdict
dd = defaultdict(list)
dd['key'].append(1) # No KeyError
# Invert dictionary (unique values)
inverted = {v: k for k, v in original_dict.items()}
# Map and filter
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
# Any and all
any_negative = any(x < 0 for x in nums)
all_positive = all(x > 0 for x in nums)
# Sorting with multiple keys
people = [{'name':'Alice','age':25}, {'name':'Bob','age':30}]
sorted_people = sorted(people, key=lambda x: (x['age'], x['name']))
# Read file
with open('file.txt', 'r') as f:
content = f.read()
# Write file
with open('output.txt', 'w') as f:
f.write("Hello\nWorld")
# Read lines
with open('data.csv') as f:
lines = [line.strip() for line in f]
from collections import defaultdict, Counter, deque
# Counter
counts = Counter('abracadabra') # {'a':5, 'b':2...}
# Deque (double-ended queue)
d = deque([1, 2, 3])
d.appendleft(0) # [0, 1, 2, 3]
d.pop() # Removes 3
from itertools import permutations, combinations, product
# Combinations
list(combinations('ABC', 2)) # [('A','B'), ('A','C'), ('B','C')]
# Cartesian product
list(product([1,2], ['a','b'])) # [(1,'a'), (1,'b'), (2,'a'), (2,'b')]
from datetime import datetime, timedelta
# Current time
now = datetime.now()
# Time delta
tomorrow = now + timedelta(days=1)
# Formatting
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
My simple library
..of useful code