📓 Python Programming - Advanced Python Concepts


1. Lambda Functions (Anonymous Functions)

  • lambda creates small, one-line, anonymous functions.

  • Often used with map(), filter(), sorted(), etc.

➤ Example:

# Regular function
def square(x):
    return x ** 2

print(square(5))

# Lambda function
square_lambda = lambda x: x ** 2
print(square_lambda(5))

2. Generators & Iterators

Generators: - Use yield to produce a sequence of values lazily (one at a time).

  • Saves memory compared to lists.

Iterators: - Any object with __iter__() and __next__() methods.

➤ Generator Example:

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1
print(count_up_to(5))  # This will print a generator object
print(list(count_up_to(5)))
for num in count_up_to(5):
    print(num)

➤ Iterator Example:

nums = [1, 2, 3]
it = iter(nums)

print(next(it))
print(next(it))
print(next(it))

3. List Comprehensions

A concise way to create lists in a single line.

➤ Example:

# Without list comprehension
squares = []
for i in range(5):
    squares.append(i ** 2)
print(squares)

# With list comprehension
squares = [i ** 2 for i in range(5)]
print(squares)

# With condition
evens = [i for i in range(10) if i % 2 == 0]
print(evens)

4. Working with args and *kwargs

  • *args: Allows variable number of positional arguments.

  • **kwargs: Allows variable number of keyword arguments.

➤ Example with *args:

def add(*numbers):
    total = sum(numbers)
    print("Sum:", total)

add(1, 2, 3)
add(4, 5)

➤ Example with **kwargs:

def student_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

student_info(name="Alice", age=21, grade="A")

➤ Using map() Function:

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared)

➤ Using filter() Function:

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)

➤ Using reduce() Function - reduce() applies a function cumulatively to the items of a sequence.

  • It is part of the functools module.
from functools import reduce

# Multiply all numbers in a list
nums = [1, 2, 3, 4]

product = reduce(lambda x, y: x * y, nums)
print(product)
nums = [5, 10, 15]

total_sum = reduce(lambda x, y: x + y, nums)
print(total_sum)

➤ Using enumerate():

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

🎯 Quick Recap

  • map(): Apply function to all items

  • filter(): Filter items based on condition

  • reduce(): Cumulatively apply function to reduce a sequence to a single value

  • Lambda: One-line anonymous functions

  • Generators: Produce values lazily with yield

  • Iterators: Objects used to iterate over sequences

  • List comprehensions: Compact way to build lists

  • args, *kwargs: Flexible argument handling

📝 Practice Exercises

  1. Write a lambda function to multiply two numbers.

  2. Create a generator that yields even numbers from 1 to 10.

  3. Use list comprehension to create a list of squares for numbers 1 to 5.

  4. Write a function that accepts any number of arguments and prints their sum using *args.

  5. Write a function that accepts student details as keyword arguments and prints them.

  6. Use map() and filter() to square numbers and filter odd numbers from a list.