⬅ Previous Next ➡

Advanced Python Concepts

Iterators (Basics)
  • Iterable: object you can loop over (list, tuple, string).
  • Iterator: object that gives values one by one using __iter__() and __next__().
  • Create iterator using iter(), get next value using next().
nums = [10, 20, 30]
it = iter(nums)

print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
Generators (yield)
  • Generator produces values lazily (one at a time) using yield.
  • Saves memory for large data.
  • Generator function returns a generator object.
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(5):
    print(x)
Generator Expression
  • Short generator form like list comprehension but uses ().
  • Values are generated on demand (memory efficient).
gen = (x * x for x in range(1, 6))

print(next(gen))  # 1
print(next(gen))  # 4
Decorators (Function Wrapper)
  • Decorator adds extra functionality to a function without changing its code.
  • Uses @decorator_name syntax.
def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@my_decorator
def hello():
    print("Hello")

hello()
Closures
  • Closure = inner function remembers variables from outer function even after outer function ends.
  • Used for function factories and data hiding.
def outer(msg):
    def inner():
        print(msg)
    return inner

f = outer("Welcome")
f()   # Welcome
Comprehensions (List, Set, Dict)
  • Comprehensions create collections in one line.
  • Types: list [], set {}, dict {k:v}.
# List comprehension
squares = [x * x for x in range(1, 6)]

# Set comprehension
unique = {x % 3 for x in range(1, 10)}

# Dict comprehension
d = {x: x * x for x in range(1, 6)}

print(squares)
print(unique)
print(d)
map() Function
  • map(function, iterable) applies function to every item.
  • Returns an iterator (convert to list if needed).
nums = [1, 2, 3, 4]

result = list(map(lambda x: x * 2, nums))
print(result)   # [2, 4, 6, 8]
filter() Function
  • filter(function, iterable) keeps items where function returns True.
  • Returns an iterator.
nums = [1, 2, 3, 4, 5, 6]

evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)   # [2, 4, 6]
reduce() Function
  • reduce() is in functools module.
  • It reduces iterable to a single value (sum/product/max, etc.).
from functools import reduce

nums = [1, 2, 3, 4]

total = reduce(lambda a, b: a + b, nums)
product = reduce(lambda a, b: a * b, nums)

print(total)     # 10
print(product)   # 24
zip() Function
  • zip() combines multiple iterables element-wise.
  • Stops at the shortest iterable.
names = ["A", "B", "C"]
marks = [80, 90, 85]

paired = list(zip(names, marks))
print(paired)   # [('A', 80), ('B', 90), ('C', 85)]
enumerate() Function
  • enumerate() gives (index, value) while looping.
  • Can start from custom index.
items = ["Python", "C", "Java"]

for i, val in enumerate(items, start=1):
    print(i, val)
Type Hints (Basics)
  • Type hints improve readability and help IDEs and linters.
  • Python still runs dynamically; hints are optional.
def add(a: int, b: int) -> int:
    return a + b

name: str = "Sourav"
marks: list[int] = [80, 90, 85]

print(add(10, 20))
Memory Management (GC and References)
  • Python uses automatic memory management.
  • Uses reference counting and garbage collector (gc) for unused objects.
  • del decreases reference count (object removed when count becomes 0).
import gc

a = [1, 2, 3]
b = a            # reference count increases

del a            # reference count decreases
gc.collect()     # forces garbage collection (optional)

print(b)
⬅ Previous Next ➡