Advance Functions
✕1. ⚡ Lambda Functions
- 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.
- 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 Functiondef square(x): return x ** 2Lambda Function:square = lambda x: x ** 2print(square(5))# ➜ 25 📌 Lambda functions are useful for short, simple operations. - 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))# ➜ Yesprint(even_check(5))# ➜ No Equivalent Normal Functiondef check_even(x): if x % 2 == 0: return "Yes" else: return "No"📌 For complex logic, use normaldeffunction instead of lambda.
1.1 What are Function Tools?
1.2 What is Lambda Function?
1.3 Example of Lambda Functions
2. 🔍 filter() Function
- 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 insidefilter()should return True or False. Syntax:filter(function, sequence)📌filter()returns a filter object. 📌 Uselist()to display the result as a list. Example - 1:numbers = [1, 2, 3, 4, 5]even_checker = lambda x: x % 2 == 0even_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]
2.1 What is filter()?
3. 🔁 map() Function
- 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. 📌 Uselist()to display the result as a list. Example:numbers = [1, 2, 3, 4, 5]square_function = lambda x: x ** 2squared_numbers = list(map(square_function, numbers))print(squared_numbers)# ➜ [1, 4, 9, 16, 25] 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.
3.1 What is map()?
3.2 Using map() for Type Conversion
4. 🧮 reduce() Function
- 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 fromfunctools. 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 namesumbecausesumis already a built-in function in Python.
4.1 What is reduce()?
5. 📦 Variable Positional Arguments: *args
*argsis 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.def product_all(*args):total = 1for num in args:total = total * numreturn totalresult = product_all(1, 2, 3, 4)print(result)# ➜ 24 📌 Use*argswhen the number of input values is not fixed.
5.1 What is *args?
5.2 *args Example
6. 🏷️ Variable Keyword Arguments: **kwargs
**kwargsis 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.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**kwargswhen the number of keyword inputs is not fixed.
6.1 What is **kwargs?
6.2 **kwargs Example
Practice QuestionsNot started
1. Lambda, map(), filter(), and reduce()
Question 1 of 2
- Write a lambda function to calculate cube of a number.
- Store
my_numas[1, 4, 7, 9, 12, 18]. Usefilter()to select multiples of 3. - Store
my_numas[1, 4, 7]. Usemap()to calculate cube of each number. - Store
my_numas[1, 5, 7, 9]. Usereduce()to calculate product of these numbers. - Store
namesas["ram", "hari", "sita"]. Usemap()to convert all names to uppercase.
1.1 Practice tasks using lambda, map(), filter(), and reduce():2. *args and **kwargs
Question 2 of 2
- Write a function
sum_all(*args)that takes any number of numbers and returns their sum. - Write a function
product_all(*args)that takes any number of numbers and returns their product. - Write a function
print_student_info(**kwargs)that displays all key-value pairs passed to it. - Write a function
create_profile(**kwargs)that returns the received keyword arguments as a dictionary. - Write a function
show_order(customer_name, *items)that displays customer name and all ordered items.
2.1 Practice tasks using *args and **kwargs:- Write a function
