DEV Community

Aruna Arun
Aruna Arun

Posted on

Day 19 : Python Programming

Advanced Python (Full Content)

Topics Covered

  1. Iterators
  2. Generators
  3. Decorators
  4. Closures
  5. Map, Filter, Reduce
  6. *args & **kwargs (Advanced usage)

1. Iterators in Python
An iterator is an object that contains a sequence of values and can be traversed one by one.
Examples:

  • list
  • tuple
  • string
  • set

Iterator Example
nums = [1, 2, 3, 4]
it = iter(nums)
print(next(it))
print(next(it))

Using Iterator in for loop
for x in nums:
print(x)

Custom Iterator Class
class Count:
def init(self, max):
self.num = 1
self.max = max
def iter(self):
return self
def next(self):
if self.num <= self.max:
val = self.num
self.num += 1
return val
else:
raise StopIteration
c = Count(5)
for i in c:
print(i)

2. Generators
A generator is a function that returns values one at a time using yield.
*Memory efficient
*Faster than list for large data

Generator Example
def numbers():
yield 1
yield 2
yield 3
for n in numbers():
print(n)

Generator with Loop
def even(n):
for i in range(2, n+1, 2):
yield i
for x in even(10):
print(x)

Difference: return vs yield

return yield
Ends function Pauses function
Returns single value Returns multiple values
Not memory efficient Memory efficient

3. Decorators
A decorator is a function that modifies another function without changing its code.
Used for:

  • Logging
  • Authentication
  • Timing
  • Access control

Simple Decorator Example
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def hello():
print("Hello World")
hello()

Decorator with Arguments
def smart_divide(func):
def wrapper(a, b):
if b == 0:
print("Cannot divide by zero")
else:
func(a, b)
return wrapper
@smart_divide
def divide(a, b):
print(a / b)
divide(10, 2)
divide(10, 0)

4. Closures
A closure is a function inside another function that remembers outer variable values.

Closure Example
def outer(x):
def inner(y):
return x + y
return inner
add5 = outer(5)
print(add5(3))

5. map(), filter(), reduce()

Used for functional programming.
map() – Apply function to all elements
nums = [1, 2, 3, 4]
result = list(map(lambda x: x*x, nums))
print(result)

filter() – Select elements
nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)

reduce() – Combine elements
from functools import reduce
nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a+b, nums)
print(total)

6. *args & **kwargs (Advanced)
**args – Multiple positional arguments*
def total(*args):
return sum(args)
print(total(1, 2, 3, 4))

kwargs – Multiple keyword arguments
def details(**kwargs):
for k, v in kwargs.items():
print(k, v)
details(name="Aruna", role="DevOps")

Function with args + kwargs
def func(a, b, *args, **kwargs):
print(a, b)
print(args)
print(kwargs)
func(1, 2, 3, 4, name="Python")

7. Real-Time Use Case (DevOps)
Execution Time Decorator
import time
def timer(func):
def wrapper():
start = time.time()
func()
end = time.time()
print("Execution time:", end-start)
return wrapper
@timer
def task():
time.sleep(2)
task()

Top comments (0)