SHREYA SARVAN MASANAM’s Post

Day 27 --Lambda Functions in Python Lambda Functions are small, anonymous functions that can be written in a single line. They are useful when you need a quick function for a short period of time and don’t want to formally define it using def. 🔹 Basic Syntax lambda arguments: expression 🔹 Example add = lambda a, b: a + b print(add(5, 3)) Output: 8 Here, the lambda function takes two arguments and returns their sum. 🔹 Using Lambda with map() map()--->The map() function is used to apply a specific function to every item in an iterable such as a list, tuple, or set. It returns a map object, so we usually convert it to a list to see the result. MAP SYNTAX:-map(function, iterable) function → the function you want to apply iterable → the list, tuple, or other collection of items EXAMPLE : Using Lambda with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) Output: [1, 4, 9, 16, 25] 🔹 Using Lambda with filter() FILTER()--->The filter() function is used to select elements from an iterable based on a condition. It returns only the elements that satisfy the condition. SYNTAX:-filter(function, iterable) function → a function that returns True or False iterable → the collection of items to filter EXAMPLE : Using Lambda with filter() numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) Output: [2, 4, 6] EXAMPLE : Using Lambda with sorted() numbers =[1,2,3,4,5,6] sorted(numbers, key=lambda x:-x)# [6, 5, 4, 3, 2, 1] Key Points *Lambda functions are anonymous functions. *They are written in a single expression. *Commonly used with functions like map(), filter(), and sorted(). *Useful for short, simple operations. Learning concepts like this helps me understand how Python can write clean and concise code. Do you prefer lambda or regular def functions? Drop your answer below 👇 #Python #PythonLearning #CodingJourney #Programming

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories