Lambda Functions and Modules in Python
Introduction
As your Python projects grow, it’s important to write clean and modular code.
Today you’ll learn two powerful concepts:
-
Lambda Functions – small, anonymous functions
-
Modules – reusable files containing Python code
1. What Is a Lambda Function?
A lambda function is a small anonymous function (a function without a name).
It is often used for short, simple operations where defining a full function isn’t necessary.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
Output:
25
2. Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
3. Using Lambda with Built-in Functions
Lambda is often used with map(), filter(), and reduce().
Example using map()
:
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)
Output:
[1, 4, 9, 16, 25]
Example using filter()
:
nums = [10, 15, 20, 25, 30]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
Output:
[10, 20, 30]
4. What Is a Module?
A module is a Python file containing definitions of functions, variables, and classes.
Modules allow you to organize your code into separate files for reusability.
Example: Create a file mymodule.py
def greet(name):
return f"Hello, {name}!"
Import and use it in another file:
import mymodule
print(mymodule.greet("Habbit2Code"))
Output:
Hello, Habbit2Code
5. Importing Specific Items
You can import only what you need.
from math import sqrt
print(sqrt(16))
Output:
4.0
6. Renaming a Module (Alias)
import math as m
print(m.pi)
Output:
3.141592653589793
7. Built-in Modules
Python provides several useful built-in modules:
-
math
→ mathematical operations -
datetime
→ date and time handling -
os
→ operating system interaction -
random
→ generate random numbers
Example:
import random
print(random.randint(1, 10))
Output:
7
Why Use Modules?
- Organize code into manageable pieces
- Reuse existing code
- Avoid redundancy
- Improve readability
Challenge for You
Create a module named calc.py
containing functions for add
, subtract
, multiply
, and divide
.
Import it into another file and perform sample calculations.
Final Thoughts
-
Lambda functions make your code concise and functional.
-
Modules make your code organized and reusable.
Together, they help you write clean, professional-quality Python programs.
In the next lesson, we’ll learn about File Handling in Python — reading and writing data to files.
Comments
Post a Comment