TGViewer
Python Learning Python Learning @python_bds · 5.74K subscribers
Post #1181 1.52K
🐍 Python Lambda Functions (Anonymous Functions) 👻

Lambda functions are small, anonymous (unnamed) functions defined with the lambda keyword. They can take any number of arguments but can only have one expression.

🔹 1. What is a Lambda Function?

A compact way to write simple functions without def. They are essentially a shortcut for defining simple, inline functions.

Syntax:
lambda arguments: expression
Example:python
add_ten = lambda x: x + 10
print(add_ten(5))

Output: 15

🔹 2. Why Use Lambda?

• Conciseness: Shorter syntax for simple operations.
• Anonymity: No need to name a function that will only be used once.
• Readability: Can make code cleaner when used appropriately in specific contexts.

🔹 3. Lambda with Multiple Arguments

Lambdas can take multiple arguments, just like regular functions.

Example:
multiply = lambda a, b: a × b
print(multiply(4, 7))

Output: 28

🔹 4. Common Use Case 1: filter()

The filter() function constructs an iterator from elements of an iterable for which a function returns True. Lambdas are often used as this function.

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

Output: [2, 4, 6]

🔹 5. Common Use Case 2: map()

The map() function applies a given function to each item of an iterable and returns an iterator of the results.

Example:
numbers = [1, 2, 3]
squared_numbers = list(map(lambda x: x × x, numbers))
print(squared_numbers)

Output: [1, 4, 9]

🔹 6. Common Use Case 3: sorted() (Custom Sort Key)

Lambdas are frequently used with sorted() as the key argument to define custom sorting logic.

Example:
students = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
# Sort by age (the second element of each tuple)
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)

Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]

🎯 Today's Goal

✔️ Understand what lambda functions are
✔️ Write short, single-expression functions
✔️ Use lambdas effectively with filter(), map(), and sorted()
  • ❤ 4
More from @python_bds
  1. Oct 8, 2026🐛 This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  2. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  3. Oct 4, 2026Python Set Methods ✍️
  4. Oct 3, 2026Post #1310
  5. Oct 1, 2026🐍 Python Beginner Notes
  6. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →