✨ Topic: Python Projects ✨
📖 Explore project-based Python tutorials and gain practical coding skills. Work on Python projects that help you gain real-world programming experience. These projects include full source code and step-by-step instructions, and will make you more confident in tackling real-world coding challenges.
🏷️ #68_resources
📖 Explore project-based Python tutorials and gain practical coding skills. Work on Python projects that help you gain real-world programming experience. These projects include full source code and step-by-step instructions, and will make you more confident in tackling real-world coding challenges.
🏷️ #68_resources
✨ Topic: NumPy ✨
📖 Master NumPy so you can perform complex mathematical operations on large data sets. NumPy is an industry-standard Python library that supports large multidimensional arrays and matrices, and mathematical functions to operate on them.
🏷️ #32_resources
📖 Master NumPy so you can perform complex mathematical operations on large data sets. NumPy is an industry-standard Python library that supports large multidimensional arrays and matrices, and mathematical functions to operate on them.
🏷️ #32_resources
✨ Topic: Python GUI Programming ✨
📖 Learn to create GUIs using various Python frameworks. From Tkinter to PyQT or wxPython, get started with GUI programming in Python. With these skills, you can develop user-friendly interfaces for your applications.
🏷️ #25_resources
📖 Learn to create GUIs using various Python frameworks. From Tkinter to PyQT or wxPython, get started with GUI programming in Python. With these skills, you can develop user-friendly interfaces for your applications.
🏷️ #25_resources
❤1
In Python, you can unpack sequences using *, to work with a variable number of elements. The * can be placed anywhere and it will collect all the extra elements into a separate variable.
👉 @DataScience4
a, b, c = 10, 2, 3 # Standard unpacking
a, *b = 10, 2, 3 # b = [2, 3]
a, *b, c = 10, 2, 3, 4 # b = [2, 3]
*a, b, c = 10, 2, 3, 4 # a = [10, 2]
Please open Telegram to view this post
VIEW IN TELEGRAM
👏2
In Python, generators are memory-efficient iterables created with functions using
🆘 @DataScience4
yield instead of return, allowing lazy evaluation for large datasets or infinite sequences. They're ideal for advanced scenarios like streaming data or coroutines.def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Usage: list(fibonacci(10)) -> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Please open Telegram to view this post
VIEW IN TELEGRAM
👍5
In Python, enhanced
#python #forloops #enumerate #bestpractices
✉️ @DataScience4
for loops with enumerate() provide both the index and value of items in an iterable, making it ideal for tasks needing positional awareness without manual counters. This is more Pythonic and efficient than using range(len()) for list traversals.fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
# With start offset:
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
# 1: apple
# 2: banana
# 3: cherry
#python #forloops #enumerate #bestpractices
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
Forwarded from Machine Learning with Python
In Python, lists are versatile mutable sequences with built-in methods for adding, removing, searching, sorting, and more—covering all common scenarios like dynamic data manipulation, queues, or stacks. Below is a complete breakdown of all list methods, each with syntax, an example, and output, plus key built-in functions for comprehensive use.
📚 Adding Elements
⦁ append(x): Adds a single element to the end.
⦁ extend(iterable): Adds all elements from an iterable to the end.
⦁ insert(i, x): Inserts x at index i (shifts elements right).
📚 Removing Elements
⦁ remove(x): Removes the first occurrence of x (raises ValueError if not found).
⦁ pop(i=-1): Removes and returns the element at index i (default: last).
⦁ clear(): Removes all elements.
📚 Searching and Counting
⦁ count(x): Returns the number of occurrences of x.
⦁ index(x[, start[, end]]): Returns the lowest index of x in the slice (raises ValueError if not found).
📚 Ordering and Copying
⦁ sort(key=None, reverse=False): Sorts the list in place (ascending by default; stable sort).
⦁ reverse(): Reverses the elements in place.
⦁ copy(): Returns a shallow copy of the list.
📚 Built-in Functions for Lists (Common Cases)
⦁ len(lst): Returns the number of elements.
⦁ min(lst): Returns the smallest element (raises ValueError if empty).
⦁ max(lst): Returns the largest element.
⦁ sum(lst[, start=0]): Sums the elements (start adds an offset).
⦁ sorted(lst, key=None, reverse=False): Returns a new sorted list (non-destructive).
These cover all standard operations (O(1) for append/pop from end, O(n) for most others). Use slicing
#python #lists #datastructures #methods #examples #programming
⭐ @DataScience4
📚 Adding Elements
⦁ append(x): Adds a single element to the end.
lst = [1, 2]
lst.append(3)
print(lst) # Output: [1, 2, 3]
⦁ extend(iterable): Adds all elements from an iterable to the end.
lst = [1, 2]
lst.extend([3, 4])
print(lst) # Output: [1, 2, 3, 4]
⦁ insert(i, x): Inserts x at index i (shifts elements right).
lst = [1, 3]
lst.insert(1, 2)
print(lst) # Output: [1, 2, 3]
📚 Removing Elements
⦁ remove(x): Removes the first occurrence of x (raises ValueError if not found).
lst = [1, 2, 2]
lst.remove(2)
print(lst) # Output: [1, 2]
⦁ pop(i=-1): Removes and returns the element at index i (default: last).
lst = [1, 2, 3]
item = lst.pop(1)
print(item, lst) # Output: 2 [1, 3]
⦁ clear(): Removes all elements.
lst = [1, 2, 3]
lst.clear()
print(lst) # Output: []
📚 Searching and Counting
⦁ count(x): Returns the number of occurrences of x.
lst = [1, 2, 2, 3]
print(lst.count(2)) # Output: 2
⦁ index(x[, start[, end]]): Returns the lowest index of x in the slice (raises ValueError if not found).
lst = [1, 2, 3, 2]
print(lst.index(2)) # Output: 1
📚 Ordering and Copying
⦁ sort(key=None, reverse=False): Sorts the list in place (ascending by default; stable sort).
lst = [3, 1, 2]
lst.sort()
print(lst) # Output: [1, 2, 3]
⦁ reverse(): Reverses the elements in place.
lst = [1, 2, 3]
lst.reverse()
print(lst) # Output: [3, 2, 1]
⦁ copy(): Returns a shallow copy of the list.
lst = [1, 2]
new_lst = lst.copy()
print(new_lst) # Output: [1, 2]
📚 Built-in Functions for Lists (Common Cases)
⦁ len(lst): Returns the number of elements.
lst = [1, 2, 3]
print(len(lst)) # Output: 3
⦁ min(lst): Returns the smallest element (raises ValueError if empty).
lst = [3, 1, 2]
print(min(lst)) # Output: 1
⦁ max(lst): Returns the largest element.
lst = [3, 1, 2]
print(max(lst)) # Output: 3
⦁ sum(lst[, start=0]): Sums the elements (start adds an offset).
lst = [1, 2, 3]
print(sum(lst)) # Output: 6
⦁ sorted(lst, key=None, reverse=False): Returns a new sorted list (non-destructive).
lst = [3, 1, 2]
print(sorted(lst)) # Output: [1, 2, 3]
These cover all standard operations (O(1) for append/pop from end, O(n) for most others). Use slicing
lst[start:end:step] for advanced extraction, like lst[1:3] outputs ``.#python #lists #datastructures #methods #examples #programming
Please open Telegram to view this post
VIEW IN TELEGRAM
❤6
In Python, list comprehensions provide a concise way to create lists by applying an expression to each item in an iterable, often with conditions—making code more readable and efficient for tasks like filtering or transforming data, a frequent interview topic for assessing Pythonic style.
#python #listcomprehensions #interviewtips #pythonic #datastructures
👉 @DataScience4
# Basic comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# Nested with transformation
matrix = [[1, 2], [3, 4]]
flattened = [num for row in matrix for num in row] # [1, 2, 3, 4]
# Equivalent to loop (interview comparison)
result = []
for x in range(5):
result.append(x**2)
# result = [0, 1, 4, 9, 16] # Same as first example
#python #listcomprehensions #interviewtips #pythonic #datastructures
👉 @DataScience4
In Python programming exams, follow these structured steps to solve problems methodically, staying focused and avoiding panic: Start by reading the problem twice to clarify inputs, outputs, and constraints—write them down simply. Break it into small sub-problems (e.g., "handle edge cases first"), plan pseudocode or a flowchart on paper, then implement step-by-step with test cases for each part, debugging one issue at a time while taking deep breaths to reset if stuck.
This approach builds confidence—practice on platforms like LeetCode to make it habit! #python #problemsolving #codingexams #debugging #interviewtips
👉 @DataScience4
# Example: Solve "Find max in list" problem step-by-step
# Step 1: Understand - Input: list of nums; Output: max value; Constraints: empty list?
def find_max(numbers):
if not numbers: # Step 2: Handle edge case (empty list)
return None # Or raise ValueError
max_val = numbers # Step 3: Initialize with first element
for num in numbers[1:]: # Step 4: Loop through rest (sub-problem: compare)
if num > max_val:
max_val = num
return max_val # Step 5: Return result
# Step 6: Test cases
print(find_max([3, 1, 4, 1, 5])) # Output: 5
print(find_max([])) # Output: None
print(find_max()) # Output: 10
# If stuck: Comment code to trace, or simplify (e.g., use max() built-in first to verify)
This approach builds confidence—practice on platforms like LeetCode to make it habit! #python #problemsolving #codingexams #debugging #interviewtips
👉 @DataScience4
🔥2
In Python, for loops are versatile for iterating over iterables like lists, strings, or ranges, but advanced types include basic iteration, index-aware with enumerate(), parallel with zip(), nested for multi-level data, and comprehension-based—crucial for efficient data processing in interviews without overcomplicating.
#python #forloops #range #enumerate #zip #nestedloops #listcomprehension #interviewtips #iteration
👉 @DataScience4
# Basic for loop over iterable (list)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # Iterates each element directly
print(fruit) # Output: apple \n banana \n cherry
# For loop with range() for numeric sequences
for i in range(3): # Generates 0, 1, 2 (start=0, stop=3, step=1)
print(i) # Output: 0 \n 1 \n 2
for i in range(1, 6, 2): # Start=1, stop=6, step=2
print(i) # Output: 1 \n 3 \n 5
# Index-aware with enumerate() (gets both index and value)
for index, fruit in enumerate(fruits, start=1): # start=1 for 1-based indexing
print(f"{index}: {fruit}") # Output: 1: apple \n 2: banana \n 3: cherry
# Parallel iteration with zip() (pairs multiple iterables)
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages): # Stops at shortest iterable
print(f"{name} is {age} years old") # Output: Alice is 25 years old \n Bob is 30 years old \n Charlie is 35 years old
# Nested for loops (outer for rows, inner for columns; e.g., matrix)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix: # Outer: each sublist
for num in row: # Inner: each element in row
print(num, end=' ') # Output: 1 2 3 4 5 6 7 8 9 (space-separated)
# For loop in list comprehension (concise iteration with optional condition)
squares = [x**2 for x in range(5)] # Basic comprehension
print(squares) # Output: [0, 1, 4, 9, 16]
evens_squared = [x**2 for x in range(10) if x % 2 == 0] # With condition (if)
print(evens_squared) # Output: [0, 4, 16, 36, 64]
# Nested comprehension (flattens 2D list)
flattened = [num for row in matrix for num in row] # Equivalent to nested for
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
#python #forloops #range #enumerate #zip #nestedloops #listcomprehension #interviewtips #iteration
👉 @DataScience4
❤2
✨ How to Serve a Website With FastAPI Using HTML and Jinja2 ✨
📖 Use FastAPI to render Jinja2 templates and serve dynamic sites with HTML, CSS, and JavaScript, then add a color picker that copies hex codes.
🏷️ #intermediate #api #front-end #web-dev
📖 Use FastAPI to render Jinja2 templates and serve dynamic sites with HTML, CSS, and JavaScript, then add a color picker that copies hex codes.
🏷️ #intermediate #api #front-end #web-dev
❤1
✨ text corpora | AI Coding Glossary ✨
📖 Curated collections of machine-readable text that serve as data resources for linguistics and natural language processing.
🏷️ #Python
📖 Curated collections of machine-readable text that serve as data resources for linguistics and natural language processing.
🏷️ #Python
✨ Python MarkItDown: Convert Documents Into LLM-Ready Markdown ✨
📖 Get started with Python MarkItDown to turn PDFs, Office files, images, and URLs into clean, LLM-ready Markdown in seconds.
🏷️ #intermediate #ai #tools
📖 Get started with Python MarkItDown to turn PDFs, Office files, images, and URLs into clean, LLM-ready Markdown in seconds.
🏷️ #intermediate #ai #tools
❤4
In Python interviews, understanding common algorithms like binary search is crucial for demonstrating problem-solving efficiency—often asked to optimize time complexity from O(n) to O(log n) for sorted data, showing your grasp of divide-and-conquer strategies.
#python #algorithms #binarysearch #interviews #timescomplexity #problemsolving
👉 @DataScience4
# Basic linear search (O(n) - naive approach)
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
nums = [1, 3, 5, 7, 9]
print(linear_search(nums, 5)) # Output: 2
# Binary search (O(log n) - efficient for sorted arrays)
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right: # Divide range until found or empty
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1 # Search right half
else:
right = mid - 1 # Search left half
return -1
sorted_nums = [1, 3, 5, 7, 9]
print(binary_search(sorted_nums, 5)) # Output: 2
print(binary_search(sorted_nums, 6)) # Output: -1 (not found)
# Edge cases
print(binary_search([], 1)) # Output: -1 (empty list)
print(binary_search(, 1)) # Output: 0 (single element)
#python #algorithms #binarysearch #interviews #timescomplexity #problemsolving
👉 @DataScience4
❤4
In Python, loops are essential for repeating code efficiently: for loops iterate over known sequences (like lists or ranges) when you know the number of iterations, while loops run based on a condition until it's false (ideal for unknown iteration counts or sentinel values), and nested loops handle multi-dimensional data by embedding one inside another—use break/continue for control, and comprehensions for concise alternatives in interviews.
#python #loops #forloop #whileloop #nestedloops #comprehensions #interviewtips #controlflow
👉 @DataScience4
# For loop: Use for fixed iterations over iterables (e.g., processing lists)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # Iterates each element
print(fruit) # Output: apple \n banana \n cherry
for i in range(3): # Numeric sequence (start=0, stop=3)
print(i) # Output: 0 \n 1 \n 2
# While loop: Use when iterations depend on a dynamic condition (e.g., user input, convergence)
count = 0
while count < 3: # Runs as long as condition is True
print(count)
count += 1 # Increment to avoid infinite loop! Output: 0 \n 1 \n 2
# Nested loops: Use for 2D data (e.g., matrices, grids); outer for rows, inner for columns
matrix = [[1, 2], [3, 4]]
for row in matrix: # Outer: each sublist
for num in row: # Inner: elements in row
print(num) # Output: 1 \n 2 \n 3 \n 4
# Control statements: break (exit loop), continue (skip iteration)
for i in range(5):
if i == 2:
continue # Skip 2
if i == 4:
break # Exit at 4
print(i) # Output: 0 \n 1 \n 3
# List comprehension: Concise for loop alternative (use for simple transformations/filtering)
squares = [x**2 for x in range(5) if x % 2 == 0] # Even squares
print(squares) # Output: [0, 4, 16]
#python #loops #forloop #whileloop #nestedloops #comprehensions #interviewtips #controlflow
👉 @DataScience4
❤3
Forwarded from PyData Careers
In Python, the
By: @DataScienceQ🚀
math module provides a wide range of mathematical functions and constants for precise computations. It supports operations like trigonometry, logarithms, powers, and more.import math
# Constants
print(math.pi) # Output: 3.141592653589793
print(math.e) # Output: 2.718281828459045
# Basic arithmetic
print(math.sqrt(16)) # Output: 4.0
print(math.pow(2, 3)) # Output: 8.0
print(math.factorial(5)) # Output: 120
# Trigonometric functions (in radians)
print(math.sin(math.pi / 2)) # Output: 1.0
print(math.cos(0)) # Output: 1.0
print(math.tan(math.pi / 4)) # Output: 0.9999999999999999
# Logarithmic functions
print(math.log(10)) # Output: 2.302585092994046
print(math.log10(100)) # Output: 2.0
print(math.log2(8)) # Output: 3.0
# Rounding functions
print(math.ceil(4.2)) # Output: 5
print(math.floor(4.8)) # Output: 4
print(math.trunc(4.9)) # Output: 4
print(round(4.5)) # Output: 4 (rounding to nearest even)
# Special functions
print(math.isfinite(10)) # Output: True
print(math.isinf(float('inf'))) # Output: True
print(math.isnan(0.0 / 0.0)) # Output: True
# Hyperbolic functions
print(math.sinh(1)) # Output: 1.1752011936438014
print(math.cosh(1)) # Output: 1.5430806348152417
# Copysign and fmod
print(math.copysign(-3, 1)) # Output: -3.0
print(math.fmod(10, 3)) # Output: 1.0
# Gamma function
print(math.gamma(4)) # Output: 6.0 (same as factorial(3))
By: @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
❤5
✨ attention mechanism | AI Coding Glossary ✨
📖 A neural network operation that computes a weighted sum of value vectors based on the similarity between a query and a set of keys.
🏷️ #Python
📖 A neural network operation that computes a weighted sum of value vectors based on the similarity between a query and a set of keys.
🏷️ #Python
✨ transformer architecture | AI Coding Glossary ✨
📖 A neural network design that models sequence dependencies using self-attention instead of recurrence or convolutions.
🏷️ #Python
📖 A neural network design that models sequence dependencies using self-attention instead of recurrence or convolutions.
🏷️ #Python
In Python, the collections module offers specialized container datatypes that solve real-world coding challenges with elegance and efficiency. These tools are interview favorites for optimizing time complexity and writing clean, professional code! 💡
By: @DatascienceN🌟
#Python #CodingInterview #DataStructures #collections #Programming #TechJobs #Algorithm #LeetCode #DeveloperTips #CareerGrowth
import collections
# defaultdict - Eliminate key errors with auto-initialization
from collections import defaultdict
gradebook = defaultdict(int)
gradebook['Alice'] += 95
print(gradebook['Alice']) # Output: 95
print(gradebook['Bob']) # Output: 0
# defaultdict for grouping operations
anagrams = defaultdict(list)
words = ["eat", "tea", "tan"]
for w in words:
key = ''.join(sorted(w))
anagrams[key].append(w)
print(anagrams['aet']) # Output: ['eat', 'tea']
# Counter - Frequency analysis in one line
from collections import Counter
text = "abracadabra"
freq = Counter(text)
print(freq['a']) # Output: 5
print(freq.most_common(2)) # Output: [('a', 5), ('b', 2)]
# Counter arithmetic for problem-solving
inventory = Counter(apples=10, oranges=5)
sales = Counter(apples=3, oranges=2)
print(inventory - sales) # Output: Counter({'apples': 7, 'oranges': 3})
# namedtuple - Self-documenting data structures
from collections import namedtuple
Employee = namedtuple('Employee', 'name role salary')
dev = Employee('Alex', 'Developer', 95000)
print(dev.role) # Output: Developer
print(dev[2]) # Output: 95000
# deque - Optimal for BFS and sliding windows
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()
print(queue) # Output: deque([2, 3, 4])
queue.rotate(1)
print(queue) # Output: deque([4, 2, 3])
# OrderedDict - Track insertion order (LRU cache essential)
from collections import OrderedDict
cache = OrderedDict()
cache['A'] = 1
cache['B'] = 2
cache.move_to_end('A')
cache.popitem(last=False)
print(list(cache.keys())) # Output: ['B', 'A']
# ChainMap - Manage layered configurations
from collections import ChainMap
defaults = {'theme': 'dark', 'font': 'Arial'}
user_prefs = {'theme': 'light'}
settings = ChainMap(user_prefs, defaults)
print(settings['font']) # Output: Arial
# Practical Interview Tip: Anagram detection
print(Counter("secure") == Counter("rescue")) # Output: True
# Pro Tip: Sliding window maximum
def max_sliding_window(nums, k):
dq, result = deque(), []
for i, n in enumerate(nums):
while dq and nums[dq[-1]] < n:
dq.pop()
dq.append(i)
if dq[0] == i - k:
dq.popleft()
if i >= k - 1:
result.append(nums[dq[0]])
return result
print(max_sliding_window([1,3,-1,-3,5,3,6,7], 3)) # Output: [3,3,5,5,6,7]
# Expert Move: Custom LRU Cache implementation
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
del self.cache[key]
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
cache.get(1)
cache.put(3, 30)
print(list(cache.cache.keys())) # Output: [2, 1, 3] → Wait! Correction: Should be [1, 3] (capacity=2 triggers eviction of '2')
# Bonus: Multiset operations with Counter
primes = Counter([2, 3, 5, 7])
odds = Counter([1, 3, 5, 7, 9])
print(primes | odds) # Output: Counter({3:1, 5:1, 7:1, 2:1, 9:1, 1:1})
By: @DatascienceN🌟
#Python #CodingInterview #DataStructures #collections #Programming #TechJobs #Algorithm #LeetCode #DeveloperTips #CareerGrowth
❤1
In Python, ORM (Object-Relational Mapping) bridges the gap between object-oriented code and relational databases—mastering it is non-negotiable for backend engineering interviews and scalable application development! 🗄
# SQLAlchemy Setup - The industry standard ORM
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# Configure database connection
engine = create_engine('sqlite:///company.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
# Model Definition - Translate tables to Python classes
class Department(Base):
__tablename__ = 'departments'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
# One-to-Many relationship
employees = relationship("Employee", back_populates="department")
class Employee(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True)
name = Column(String(100))
email = Column(String(100), unique=True)
# Foreign Key
department_id = Column(Integer, ForeignKey('departments.id'))
# Relationship back-reference
department = relationship("Department", back_populates="employees")
# Create tables in database
Base.metadata.create_all(engine)
# CRUD Operations - Core interview competency
# CREATE
hr = Department(name="HR")
session.add(hr)
session.commit()
alice = Employee(name="Alice", email="alice@company.com", department=hr)
session.add(alice)
session.flush() # Assigns ID without committing
print(alice.id) # Output: 1
# READ
employee = session.query(Employee).filter_by(name="Alice").first()
print(employee.department.name) # Output: "HR"
# UPDATE
employee.email = "alice.smith@company.com"
session.commit()
# DELETE
session.delete(employee)
session.commit()
# Advanced Querying - Solve complex data challenges
from sqlalchemy import or_, and_, func
# Filter combinations
active_employees = session.query(Employee).filter(
Employee.name.like('A%'),
or_(Employee.email.endswith('@company.com'), Employee.id < 10)
)
# Aggregation
dept_count = session.query(
Department.name,
func.count(Employee.id)
).join(Employee).group_by(Department.id).all()
print(dept_count) # Output: [('HR', 1), ('Engineering', 5)]
# Pagination (critical for web apps)
page_2 = session.query(Employee).limit(10).offset(10).all()
# Relationship Handling - Avoid N+1 query disasters
# LAZY LOADING (default - causes N+1 problem)
for dept in session.query(Department):
print(dept.employees) # Triggers separate query per department
# EAGER LOADING (interview gold)
from sqlalchemy.orm import joinedload
depts = session.query(Department).options(
joinedload(Department.employees)
).all()
print(len(session.identity_map)) # Output: 6 (1 query for all data)
# Many-to-Many Relationships - Real-world schema design
# Association table
employee_projects = Table('employee_projects', Base.metadata,
Column('employee_id', Integer, ForeignKey('employees.id')),
Column('project_id', Integer, ForeignKey('projects.id'))
)
class Project(Base):
__tablename__ = 'projects'
id = Column(Integer, primary_key=True)
name = Column(String(100))
# Many-to-Many
members = relationship("Employee", secondary=employee_projects)
# Add employee to project
project = Project(name="AI Initiative")
project.members.append(alice)
session.commit()
# Transactions - Atomic operations for data integrity
from sqlalchemy.exc import SQLAlchemyError
try:
with session.begin():
alice = Employee(name="Alice", email="alice@company.com")
session.add(alice)
# Automatic rollback if error occurs
raise ValueError("Simulated error")
except ValueError:
print(session.query(Employee).count()) # Output: 0 (no partial data)
❤1