Learn PYTHON with Real Code Examples
Updated Nov 18, 2025
Code Sample Descriptions
1
Python List Comprehension and Functions
import math
from typing import List, Optional
def fibonacci(n: int) -> List[int]:
"""Generate fibonacci sequence up to n numbers"""
if n <= 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
def find_primes(limit: int) -> List[int]:
"""Find all prime numbers up to limit using sieve"""
primes = []
sieve = [True] * (limit + 1)
for i in range(2, int(math.sqrt(limit)) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return [i for i in range(2, limit + 1) if sieve[i]]
# Main execution
if __name__ == "__main__":
fib_sequence = fibonacci(10)
print(f"Fibonacci: {fib_sequence}")
primes = find_primes(30)
print(f"Primes up to 30: {primes}")
# List comprehension example
squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"Even squares: {squares}")
Demonstrates Python's list comprehension, type hints, and function definitions with docstrings.
2
Python Quick Sort Algorithm
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Example usage
if __name__ == "__main__":
data = [3, 6, 8, 10, 1, 2, 1]
print(f"Original: {data}")
sorted_data = quick_sort(data)
print(f"Sorted: {sorted_data}")
Implements the quick sort algorithm using recursion and list comprehensions in Python.
3
Python Dictionary Comprehensions
numbers = range(1, 11)
square_dict = {x: x**2 for x in numbers if x % 2 == 0}
print(f"Square dict: {square_dict}")
Using dictionary comprehensions to map squares and filter values.
4
Python Filter and Map
numbers = range(1, 11)
evens = list(filter(lambda x: x % 2 == 0, numbers))
squares = list(map(lambda x: x**2, evens))
print(f"Evens: {evens}, Squares: {squares}")
Using map and filter functions with lambda expressions.
5
Python Lambda and Reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_numbers = reduce(lambda a, b: a + b, numbers)
print(f"Sum: {sum_numbers}")
Using lambda functions with functools.reduce.
6
Python Set Comprehension
numbers = [1, 2, 2, 3, 3, 4]
squared_set = {x**2 for x in numbers}
print(f"Squared set: {squared_set}")
Using set comprehension to remove duplicates and square numbers.
7
Python Nested List Comprehension
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [num for row in matrix for num in row]
print(f"Flattened list: {flat}")
Flattening a 2D list using nested list comprehension.
8
Python Function with Optional Argument
def greet(name: str, greeting: Optional[str] = "Hello") -> None:
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", greeting="Hi")
Defining a function with an optional parameter and default value.
9
Python Zip Function
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Using zip to combine two lists and iterate over pairs.
10
Python List Comprehension with Condition
numbers = range(1, 11)
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"Even squares: {even_squares}")
Filtering and transforming a list in one comprehension.
11
Python Recursion Example
def factorial(n: int) -> int:
if n <= 1:
return 1
return n * factorial(n-1)
print(f"Factorial of 5: {factorial(5)}")
Recursive function to compute factorial.