Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Functions Module 4 - Functions Python Python Basics Python Programming: From Zero to Real-World Applications

Lambda Functions - Anonymous One-Liners in Python

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • What lambda functions are
  • When to use them vs regular functions
  • Common use cases with map, filter, sorted
Terminalpython
# Regular function
def square(x):
    return x ** 2

# Lambda equivalent
square = lambda x: x ** 2

print(square(5))   # 25

# Lambda with multiple args
add = lambda a, b: a + b
print(add(3, 4))   # 7

Common Use Cases

Terminalpython
# 1. Sorting with custom key
students = [("Anita", 85), ("Ravi", 92), ("Mira", 78)]
students.sort(key=lambda s: s[1])  # Sort by grade
print(students)   # [('Mira', 78), ('Anita', 85), ('Ravi', 92)]

# 2. map() - apply to each element
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)   # [1, 4, 9, 16, 25]

# 3. filter() - keep elements that match
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)   # [2, 4]

# 4. Default parameter in dict.get()
config = {"host": "localhost"}
port = config.get("port", lambda: 8080)()
When to use lambda
Use lambda for SHORT, one-time operations like sorting keys, map, filter. For anything complex, use a regular def function - it is more readable.

Practical Exercise

Create: square = lambda x: x**2
Call: square(5) = 25
Sort [('A',3),('B',1),('C',2)] by second element with lambda
Use map: list(map(lambda x: x*2, [1,2,3]))
Use filter: list(filter(lambda x: x>2, [1,2,3,4]))

Key Takeaways

  • Lambda = anonymous one-line function.
  • Syntax: lambda args: expression.
  • Best for: sort key, map, filter, short callbacks.
  • For complex logic, use regular def.
  • lambda cannot have statements (if, for) - only expressions.
Previously: Lesson 27 covered scope.
Today: You learned: Anonymous one-line functions.
Next: Lesson 29 covers recursion.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments