
![]() |
@wtf | |
(Process lists efficiently) |
||
1
Replies
7
Views
1 Bookmarks
|
![]() |
@wtf | 5 days |
Lambda, map(), and filter()* *What is a Lambda Function?* A lambda function is an anonymous function written in one line using the lambda keyword. ✅ *Syntax:* lambda arguments: expression *Example:* square = lambda x: x ** 2 print(square(5)) Output: 25 Use lambdas when you need a simple function for a short time — usually as an argument to map(), filter(), or sorted(). *map() — Apply a Function to All Items* Takes a function and an iterable, and applies the function to every item in the iterable. nums = [1, 2, 3, 4] squares = list(map(lambda x: x ** 2, nums)) print(squares) Output: [1, 4, 9, 16] *filter() — Filter Items Based on a Condition* Filters the iterable by applying a function that returns True/False. nums = [1, 2, 3, 4, 5, 6] even = list(filter(lambda x: x % 2 == 0, nums)) print(even) Output: [2, 4, 6] *Mini Project: Filter & Transform List* nums = list(range(1, 21)) Step 1: Keep only even numbers even_nums = list(filter(lambda x: x % 2 == 0, nums)) Step 2: Square the even numbers squared_evens = list(map(lambda x: x ** 2, even_nums)) print(Even numbers:, even_nums) print(Squared evens:, squared_evens) You just combined filtering and transformation using lambda, map, and filter! |
||


