Lesson 14
Lambda Functions
Write compact anonymous functions
1What Are Lambda Functions?✨
Lambda functions are small, anonymous functions defined with the `lambda` keyword in Python. They can take any number of parameters but only have one expression. They're perfect for quick, simple operations without the need to formally define a full function.
2Why Use Lambda Functions?🎯
- ✓ Create compact, throwaway functions
- ✓ Simplify code where functions are used once
- ✓ Make your code cleaner and more readable
3Creating a Lambda Function💡
You can create a lambda function like this:
double = lambda x: x * 2
print(double(5)) # Outputs: 10In this example, `double` is a lambda function that takes an input `x` and returns it multiplied by 2.
4Using Lambda with Functions🚀
Lambda functions are often used with higher-order functions like `map()`, `filter()`, and `sorted()`. For example, to square a list of numbers:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Outputs: [1, 4, 9, 16]5Filtering with Lambda Functions🔍
You can also filter lists using lambda functions. Here’s how to find even numbers:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Outputs: [2, 4, 6]6Lambda Functions in Sorting⭐
Lambda functions can help sort complex data structures. For example, sorting a list of tuples based on the second element:
data = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Outputs: [(1, 'apple'), (3, 'banana'), (2, 'cherry')]7Your Next Steps🧩
Now that you understand lambda functions, try using them in your own projects! Challenge yourself to apply lambda functions in various scenarios, like data processing or even creating simple games.
🎯 Practice Challenges
Master Lambda Functions by completing all 3 difficulty levels
Lambda Functions - Easy Challenge
Start with the basics. Perfect for beginners!
Lambda Functions - Medium Challenge
Get more challenging. Build your confidence!
Lambda Functions - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master Lambda Functions? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 13: RecursionFunctions that call themselves
- Next lesson →Lesson 15: Modules & ImportsOrganize code across files
- Grade 8 courseJavaScript Basics - Web ProgrammingJavaScript coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 7 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.