Python Functions,Lambda, Map, Filter, Reduce
- What is a Function? A function is a block of reusable code that performs a specific task. Example: def greet(): print("Hello!")
2. Why Use Functions?
✔ Avoid code repetition
✔ Make code clean and modular
✔ Easy to debug
✔ Increases reusability
3. Types of Functions
1.Built-in Functions
Already provided by Python
Example:
print(), len(), type(), input(), int(), float()
2.User-defined Functions
Created by the programmer
Example:
def add():
print(10 + 20)
4. Function Syntax
def function_name():
# code
5. Function with Parameters
def add(a, b):
print(a + b)
Call:
add(5, 3)
6. Function with Return Value
def square(n):
return n * n
7. Default Arguments
def greet(name="User"):
print("Hello", name)
8. Keyword Arguments
def student(name, age):
print(name, age)
student(age=20, name="Aruna")
9. Variable-Length Arguments
args (multiple values)
def total(*numbers):
print(sum(numbers))
total(2,3,4,5)
kwargs (multiple keyword values)
def info(**details):
print(details)
info(name="Aruna", age=21)
Lambda, Map, Filter, Reduce **
**1. Lambda Function
A lambda function is a small anonymous function (one-line function).
Syntax:
lambda arguments: expression
Example:
square = lambda x: x*x
print(square(5))
2. Lambda with if-else
check = lambda n: "Even" if n % 2 == 0 else "Odd"
print(check(10))
3. Map() Function
map() applies a function to each element in a list.
Example:
numbers = [1,2,3,4]
result = list(map(lambda x: x*2, numbers))
print(result) # [2,4,6,8]
4. Filter() Function
Used to filter values based on condition.
Example:
numbers = [1,2,3,4,5,6]
even = list(filter(lambda x: x%2==0, numbers))
print(even)
5. Reduce() Function
Used to reduce a list to a single value.
(Import from functools)
Example:
from functools import reduce
numbers = [1,2,3,4]
total = reduce(lambda a,b: a+b, numbers)
print(total)
6. Lambda with Strings
upper = lambda s: s.upper()
print(upper("python"))
Top comments (0)