Advanced Python concepts help write:
- Efficient code
- Cleaner programs
- Reusable and optimized solutions
Iterators in Python
An iterator is an object used to iterate through data one element at a time.
Examples of iterable objects:
- Lists
- Tuples
- Strings
- Dictionaries
Using Iterator
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
20
30
StopIteration Exception
When elements finish:
print(next(iterator))
Output:
StopIteration
Custom Iterator
class Counter:
def __init__(self, max_value):
self.max_value = max_value
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current <= self.max_value:
value = self.current
self.current += 1
return value
raise StopIteration
counter = Counter(5)
for num in counter:
print(num)
Generators in Python
Generators create iterators using yield.
Advantages:
- Memory efficient
- Faster for large data
Generator Function
def numbers():
yield 1
yield 2
yield 3
gen = numbers()
print(next(gen))
print(next(gen))
Generator with Loop
def countdown(n):
while n > 0:
yield n
n -= 1
for value in countdown(5):
print(value)
Generator Expression
squares = (x * x for x in range(5))
for num in squares:
print(num)
Decorators in Python
Decorators modify function behavior without changing original code.
Basic Decorator
def decorator_function(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
Applying Decorator
@decorator_function
def say_hello():
print("Hello")
say_hello()
Output:
Before function call
Hello
After function call
Decorator with Arguments
def smart_divide(func):
def wrapper(a, b):
if b == 0:
print("Cannot divide by zero")
return
return func(a, b)
return wrapper
@smart_divide
def divide(a, b):
print(a / b)
divide(10, 2)
divide(10, 0)
Context Managers
Context managers manage resources automatically.
Usually used with:
with
statement.
File Context Manager
with open("data.txt", "r") as file:
content = file.read()
print(content)
File closes automatically.
Custom Context Manager
class FileManager:
def __enter__(self):
print("File opened")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("File closed")
with FileManager():
print("Working with file")
Closures in Python
A closure remembers variables from outer function even after outer function finishes.
Example
def outer(message):
def inner():
print(message)
return inner
greet = outer("Hello Python")
greet()
Output:
Hello Python
Comprehensions in Python
Comprehensions provide shorter syntax for creating collections.
List Comprehension
Syntax
[expression for item in iterable]
Example
squares = [x * x for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
List Comprehension with Condition
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
Dictionary Comprehension
Syntax
{key:value for item in iterable}
Example
squares = {x: x * x for x in range(5)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Set Comprehension
numbers = {x for x in range(5)}
print(numbers)
Functional Programming Tools
Python provides built-in functional programming functions.
1. map()
Applies function to every item.
Syntax
map(function, iterable)
Example
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x * 2, numbers))
print(result)
Output:
[2, 4, 6, 8]
2. filter()
Filters elements based on condition.
Syntax
filter(function, iterable)
Example
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4, 6]
3. reduce()
Reduces iterable to single value.
Available in:
functools
module.
Example
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda a, b: a + b, numbers)
print(result)
Output:
10
Comparison of map, filter, and reduce
| Function | Purpose |
|---|---|
map() | Transform data |
filter() | Select data |
reduce() | Combine data |
Practical Example
Student Marks Processing
marks = [45, 78, 90, 32, 67]
# Passed students
passed = list(filter(lambda x: x >= 40, marks))
# Add grace marks
updated = list(map(lambda x: x + 5, passed))
print(updated)
Advantages of Advanced Concepts
✅ Cleaner code
✅ Better performance
✅ Reusable components
✅ Memory optimization
✅ Functional programming support






