Advance Functions

1. ⚡ Lambda Functions

    1.1 What are Function Tools?
    1. In the previous note, we learned how to create and call normal functions using def. Sometimes, we need to use functions in shorter or more flexible ways. For Example, we may need to: - Write a small one-line function - Apply a function to every item in a list - Select items from a list using a condition - Combine many values into one result Python provides special function tools for these tasks. In this note, we will learn: 👉 lambda 👉 filter() 👉 map() 👉 reduce() 👉 *args 👉 **kwargs 📌 These tools are commonly used with functions, lists, and data processing. 📌 For beginners, normal def functions are usually easier to read, but these tools are useful when we need shorter or more flexible code.
    1.2 What is Lambda Function?
    1. A lambda function is a short function used for small, quick tasks. It does not need a proper function name like normal def functions, so it is called an anonymous function. Syntax: lambda arguments: expressionNormal Function def square(x): return x ** 2Lambda Function: square = lambda x: x ** 2 print(square(5)) # ➜ 25 📌 Lambda functions are useful for short, simple operations.
    1.3 Example of Lambda Functions
    1. Lambda with Multiple Arguments:add = lambda x, y: x + yprint(add(3, 4)) # ➜ 7 Equivalent Normal Function: def add(x, y): return x + yLambda Returning Multiple Values:sum_diff = lambda x, y: (x + y, x - y)print(sum_diff(3, 4)) # ➜ (7, -1) Equivalent Normal Function: def sum_diff(x, y): return (x + y, x - y)Lambda with Condition:even_check = lambda x: "Yes" if x % 2 == 0 else "No"print(even_check(4)) # ➜ Yes print(even_check(5)) # ➜ No Equivalent Normal Function def check_even(x): if x % 2 == 0: return "Yes" else: return "No" 📌 For complex logic, use normal def function instead of lambda.

2. 🔍 filter() Function

    2.1 What is filter()?
    1. Imagine a security gate where every person is checked before entering. People without valid ID are stopped. filter() works in a similar way. It checks each item and keeps only the items that satisfy the condition. The function used inside filter() should return True or False. Syntax: filter(function, sequence) 📌 filter() returns a filter object. 📌 Use list() to display the result as a list. Example - 1: numbers = [1, 2, 3, 4, 5]even_checker = lambda x: x % 2 == 0 even_numbers = list(filter(even_checker, numbers)) print(even_numbers) # ➜ [2, 4] Example - 2: age_list = [15, 22, 30, 17, 40]adults = list(filter(lambda x: x >= 18, age_list)) print(adults) # ➜ [22, 30, 40]

3. 🔁 map() Function

    3.1 What is map()?
    1. Imagine a stamping machine. Every paper goes through the machine. The machine applies the same stamp to every paper. No paper is skipped. map() works in a similar way. It applies a function to each item of a sequence. It is useful when we want to transform every item. Syntax: map(function, sequence) 📌 map() returns a map object. 📌 Use list() to display the result as a list. Example: numbers = [1, 2, 3, 4, 5]square_function = lambda x: x ** 2 squared_numbers = list(map(square_function, numbers)) print(squared_numbers) # ➜ [1, 4, 9, 16, 25]
    3.2 Using map() for Type Conversion
    1. num_values = ["1", "2", "3"]int_values = list(map(int, num_values)) print(int_values) # ➜ [1, 2, 3] 📌 map() transforms every item. 📌 filter() selects only some items.

4. 🧮 reduce() Function

    4.1 What is reduce()?
    1. Imagine a knockout tournament. Two teams compete first, and one result/winner comes out. Then that winner competes with the next team. This continues until only one final winner remains. reduce() works in a similar way. It takes two values at a time, combines them, then combines the result with the next value until one final result remains. reduce() is available from functools. Syntax: from functools import reducereduce(function, sequence) 📌 reduce() is useful for combining many values into one value. Example: Product using reduce: from functools import reducenumbers = [1, 2, 3, 4]product = reduce(lambda x, y: x * y, numbers) print(product) # ➜ 24 How it worked: - Initialization: [1, 2, 3, 4] - Step 1: 1 * 2 = 2 ➜ [2, 3, 4] - Step 2: 2 * 3 = 6 ➜ [6, 4] - Step 3: 6 * 4 = 24 Final result = 24 Example: sum using reduce: from functools import reducenumbers = [1, 2, 3, 4]total_sum = reduce(lambda x, y: x + y, numbers) print(total_sum) # ➜ 10 📌 Avoid using variable name sum because sum is already a built-in function in Python.

5. 📦 Variable Positional Arguments: *args

    5.1 What is *args?
    1. *args is used when we want to pass any number of positional arguments to a function. The extra arguments are stored as a tuple. Example: def show_numbers(*args):print(args)show_numbers(1, 2, 3, 4)Output: (1, 2, 3, 4) 📌 The name args is commonly used, but * is what collects extra positional arguments.
    5.2 *args Example
    1. def product_all(*args):total = 1for num in args:total = total * numreturn totalresult = product_all(1, 2, 3, 4) print(result) # ➜ 24 📌 Use *args when the number of input values is not fixed.

6. 🏷️ Variable Keyword Arguments: **kwargs

    6.1 What is **kwargs?
    1. **kwargs is used when we want to pass any number of keyword arguments to a function. The extra keyword arguments are stored as a dictionary. Example: def print_info(**kwargs):print(kwargs)print_info(name="Alice", age=30, city="Kathmandu")Output: {"name": "Alice", "age": 30, "city": "Kathmandu"} 📌 The name kwargs is commonly used, but ** is what collects extra keyword arguments.
    6.2 **kwargs Example
    1. def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=30, city="Kathmandu")Output: name: Alice age: 30 city: Kathmandu 📌 Use **kwargs when the number of keyword inputs is not fixed.

Practice QuestionsNot started

  1. 1. Lambda, map(), filter(), and reduce()

    Question 1 of 2

      1.1 Practice tasks using lambda, map(), filter(), and reduce():
      1. Write a lambda function to calculate cube of a number.
      2. Store my_num as [1, 4, 7, 9, 12, 18]. Use filter() to select multiples of 3.
      3. Store my_num as [1, 4, 7]. Use map() to calculate cube of each number.
      4. Store my_num as [1, 5, 7, 9]. Use reduce() to calculate product of these numbers.
      5. Store names as ["ram", "hari", "sita"]. Use map() to convert all names to uppercase.
  2. 2. *args and **kwargs

    Question 2 of 2

      2.1 Practice tasks using *args and **kwargs:
      1. Write a function sum_all(*args) that takes any number of numbers and returns their sum.
      2. Write a function product_all(*args) that takes any number of numbers and returns their product.
      3. Write a function print_student_info(**kwargs) that displays all key-value pairs passed to it.
      4. Write a function create_profile(**kwargs) that returns the received keyword arguments as a dictionary.
      5. Write a function show_order(customer_name, *items) that displays customer name and all ordered items.