๐ Data Science Roadmap 2026
๐ Phase 1: Programming Fundamentals
๐ Topic 6: Python Functions
So far, you've learned variables, operators, input/output, conditional statements, and loops. As your programs grow larger, writing the same code repeatedly becomes inefficient. That's where functions come in.
A function is a reusable block of code that performs a specific task. Functions make your code cleaner, easier to maintain, and reusable.
Functions are heavily used in Data Science, Machine Learning, and AI because they allow you to organize complex workflows into smaller, manageable pieces.
๐น 1. What is a Function?
A function is a named block of code that executes only when it is called.
Instead of writing the same logic multiple times, you write it once inside a function and reuse it whenever needed.
Example
Output
๐น 2. Why Do We Use Functions?
Functions help you:
โ Avoid writing duplicate code
โ Improve code readability
โ Make debugging easier
โ Reuse code in multiple places
โ Build modular applications
๐น 3. Defining a Function
Syntax
Example:
๐น 4. Function Parameters
Parameters allow you to pass information into a function.
Output
Here, "name" is called a parameter.
๐น 5. Function Arguments
When calling a function, the values you pass are called arguments.
Output
Here:
โข "number" โ Parameter
โข "5" โ Argument
๐น 6. Returning Values
A function can return a value using the return keyword.
Output
Using return allows the function's result to be stored or used later.
๐น 7. Default Parameters
You can assign default values to parameters.
Output
๐น 8. Multiple Return Values
A function can return more than one value.
Output
๐น 9. Scope of Variables
Variables created inside a function are called local variables.
Trying to access
outside the function will produce an error because it exists only inside the function.
๐น 10. Built-in Functions
Python provides many ready-to-use functions.
Examples:
Output
๐น 11. Real-World Data Science Example
Calculate the average marks of students.
Output
Functions like this are commonly used while cleaning data, calculating statistics, and building machine learning pipelines.
๐น 12. Common Mistakes
โ Forgetting to Call the Function
Correct:
โ Forgetting to Return a Value
๐ฏ Practice Questions
1. Write a function to add two numbers.
2. Create a function to calculate the square of a number.
3. Write a function that checks whether a number is even or odd.
4. Create a function to calculate the average of a list.
5. Write a function that returns the largest of three numbers.
Double Tap โค๏ธ For Part-7
๐ Phase 1: Programming Fundamentals
๐ Topic 6: Python Functions
So far, you've learned variables, operators, input/output, conditional statements, and loops. As your programs grow larger, writing the same code repeatedly becomes inefficient. That's where functions come in.
A function is a reusable block of code that performs a specific task. Functions make your code cleaner, easier to maintain, and reusable.
Functions are heavily used in Data Science, Machine Learning, and AI because they allow you to organize complex workflows into smaller, manageable pieces.
๐น 1. What is a Function?
A function is a named block of code that executes only when it is called.
Instead of writing the same logic multiple times, you write it once inside a function and reuse it whenever needed.
Example
def greet():
print("Welcome to Data Science!")
greet()
Output
Welcome to Data Science!
๐น 2. Why Do We Use Functions?
Functions help you:
โ Avoid writing duplicate code
โ Improve code readability
โ Make debugging easier
โ Reuse code in multiple places
โ Build modular applications
๐น 3. Defining a Function
Syntax
def function_name():
# Function body
Example:
def welcome():
print("Hello, World!")
welcome()
๐น 4. Function Parameters
Parameters allow you to pass information into a function.
def greet(name):
print("Hello", name)
greet("Deepak")
Output
Hello Deepak
Here, "name" is called a parameter.
๐น 5. Function Arguments
When calling a function, the values you pass are called arguments.
def square(number):
print(number * number)
square(5)
Output
25
Here:
โข "number" โ Parameter
โข "5" โ Argument
๐น 6. Returning Values
A function can return a value using the return keyword.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output
30
Using return allows the function's result to be stored or used later.
๐น 7. Default Parameters
You can assign default values to parameters.
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Rahul")
Output
Hello Guest
Hello Rahul
๐น 8. Multiple Return Values
A function can return more than one value.
def calculate(a, b):
return a + b, a * b
sum_value, product = calculate(4, 5)
print(sum_value)
print(product)
Output
9
20
๐น 9. Scope of Variables
Variables created inside a function are called local variables.
def demo():
message = "Inside Function"
print(message)
demo()
Trying to access
message
outside the function will produce an error because it exists only inside the function.
๐น 10. Built-in Functions
Python provides many ready-to-use functions.
Examples:
numbers = [5, 2, 8, 1]
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Output
4
8
1
16
๐น 11. Real-World Data Science Example
Calculate the average marks of students.
def average(marks):
return sum(marks) / len(marks)
scores = [80, 75, 92, 88]
print(average(scores))
Output
83.75
Functions like this are commonly used while cleaning data, calculating statistics, and building machine learning pipelines.
๐น 12. Common Mistakes
โ Forgetting to Call the Function
def greet():
print("Hello")
# Nothing happens because the function isn't called.
Correct:
greet()
โ Forgetting to Return a Value
def add(a, b):
a + b
# Correct:
def add(a, b):
return a + b
๐ฏ Practice Questions
1. Write a function to add two numbers.
2. Create a function to calculate the square of a number.
3. Write a function that checks whether a number is even or odd.
4. Create a function to calculate the average of a list.
5. Write a function that returns the largest of three numbers.
Double Tap โค๏ธ For Part-7
โค18
Which keyword is used to define a function in Python?
Anonymous Quiz
8%
A) function
85%
B) def
6%
C) func
1%
D) define
โค2
Which keyword is used to return a value from a function?
Anonymous Quiz
3%
A) break
11%
B) print
84%
C) return
2%
D) pass
โค1
Which of the following is a built-in Python function?
Anonymous Quiz
15%
A) calculate()
15%
B) average()
64%
C) sum()
7%
D) multiply()
โค2
What will be the output of the following code?
def multiply(a, b):
return a * b print(multiply(4, 5))
def multiply(a, b):
return a * b print(multiply(4, 5))
Anonymous Quiz
7%
9
93%
20
โค1๐ฅฐ1
What will be the output of the following code?
def greet(): print("Hello") greet()
def greet(): print("Hello") greet()
Anonymous Quiz
91%
Hello
9%
greet
โค4
๐ Data Science Roadmap 2026
๐ Phase 1: Programming Fundamentals
๐ Topic 7: Python Data Structures (Lists, Tuples, Sets & Dictionaries)
Welcome back! ๐
So far, you've learned variables, operators, input/output, conditional statements, loops, and functions. Now it's time to learn one of the most important topics in Pythonโ Data Structures.
Data structures help us store, organize, and manage data efficiently. In Data Science, almost every dataset you work with will be stored or manipulated using these structures.
Python provides four built-in data structures:
โข List
โข Tuple
โข Set
โข Dictionary
Let's understand each one in detail.
๐น 1. List
A List is an ordered, mutable collection that allows duplicate values.
Creating a List
Output
Accessing Elements
Output
Modifying a List
Output
Adding Elements
Removing Elements
๐น 2. Tuple
A Tuple is an ordered collection that cannot be modified after creation (immutable).
Creating a Tuple
Accessing Elements
Output
Why Use Tuples?
Use tuples when your data should never change.
Examples:
โข Months of the year
โข Days of the week
โข Fixed coordinates
๐น 3. Set
A Set is an unordered collection of unique elements.
Duplicate values are automatically removed.
Creating a Set
Output
Adding Elements
Removing Elements
Common Uses
โข Remove duplicates
โข Membership testing
โข Mathematical set operations
๐น 4. Dictionary โญ
A Dictionary stores data as key-value pairs.
It is one of the most frequently used data structures in Data Science.
Creating a Dictionary
Accessing Values
Output
Adding a New Key
Updating a Value
Removing a Key
๐น 5. Comparison of Data Structures
Feature | List | Tuple | Set | Dictionary
Ordered | โ | โ | โ | โ
Mutable | โ | โ | โ | โ
Duplicates Allowed | โ | โ | โ | Keys โ
Indexed | โ | โ | โ | By Key
๐น 6. Common List Methods
๐น 7. Common Dictionary Methods
๐ Phase 1: Programming Fundamentals
๐ Topic 7: Python Data Structures (Lists, Tuples, Sets & Dictionaries)
Welcome back! ๐
So far, you've learned variables, operators, input/output, conditional statements, loops, and functions. Now it's time to learn one of the most important topics in Pythonโ Data Structures.
Data structures help us store, organize, and manage data efficiently. In Data Science, almost every dataset you work with will be stored or manipulated using these structures.
Python provides four built-in data structures:
โข List
โข Tuple
โข Set
โข Dictionary
Let's understand each one in detail.
๐น 1. List
A List is an ordered, mutable collection that allows duplicate values.
Creating a List
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
Output
['Apple', 'Banana', 'Mango']
Accessing Elements
print(fruits[0])
print(fruits[2])
Output
Apple
Mango
Modifying a List
fruits[1] = "Orange"
print(fruits)
Output
['Apple', 'Orange', 'Mango']
Adding Elements
fruits.append("Grapes")
print(fruits)Removing Elements
fruits.remove("Orange")
print(fruits)๐น 2. Tuple
A Tuple is an ordered collection that cannot be modified after creation (immutable).
Creating a Tuple
colors = ("Red", "Green", "Blue")
print(colors)Accessing Elements
print(colors[1])
Output
Green
Why Use Tuples?
Use tuples when your data should never change.
Examples:
โข Months of the year
โข Days of the week
โข Fixed coordinates
๐น 3. Set
A Set is an unordered collection of unique elements.
Duplicate values are automatically removed.
Creating a Set
numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)Output
{1, 2, 3, 4, 5}Adding Elements
numbers.add(6)
Removing Elements
numbers.remove(3)
Common Uses
โข Remove duplicates
โข Membership testing
โข Mathematical set operations
๐น 4. Dictionary โญ
A Dictionary stores data as key-value pairs.
It is one of the most frequently used data structures in Data Science.
Creating a Dictionary
student = {
"name": "Deepak",
"age": 24,
"course": "Data Science"
}
print(student)Accessing Values
print(student["name"])
Output
Deepak
Adding a New Key
student["city"] = "Mumbai"
Updating a Value
student["age"] = 25
Removing a Key
del student["course"]
๐น 5. Comparison of Data Structures
Feature | List | Tuple | Set | Dictionary
Ordered | โ | โ | โ | โ
Mutable | โ | โ | โ | โ
Duplicates Allowed | โ | โ | โ | Keys โ
Indexed | โ | โ | โ | By Key
๐น 6. Common List Methods
numbers = [10, 20, 30]
numbers.append(40)
numbers.insert(1, 15)
numbers.remove(20)
numbers.sort()
print(numbers)
๐น 7. Common Dictionary Methods
โค5
student = {
"name": "Rahul",
"age": 23
}
print(student.keys())
print(student.values())
print(student.items())๐น 8. Real-World Data Science Example
Suppose you have student information.
students = [
{"name": "Amit", "marks": 90},
{"name": "Sara", "marks": 85}
]
for student in students:
print(student["name"], student["marks"])
Output
Amit 90
Sara 85
This is very similar to how records are stored before converting them into a Pandas DataFrame.
๐น 9. Common Mistakes
โ Trying to Modify a Tuple
colors = ("Red", "Green")
colors[0] = "Blue"This raises a
TypeError because tuples are immutable.โ Accessing a Missing Dictionary Key
student = {"name": "John"}
print(student["age"])This raises a
KeyError.A safer approach:
print(student.get("age"))๐ฏ Practice Questions
1. Create a list of five cities and print the third city.
2. Create a tuple containing the days of the week.
3. Remove duplicate numbers from a list using a set.
4. Create a dictionary containing your name, age, and profession.
5. Print all keys and values of a dictionary using a loop.
๐ฏ Key Takeaways
โ Lists are ordered and mutable.
โ Tuples are ordered and immutable.
โ Sets store only unique values.
โ Dictionaries store data as key-value pairs.
โ Dictionaries and Lists are the most commonly used data structures in Data Science.
Mastering these four data structures will make it much easier to work with datasets, APIs, JSON files, and machine learning projects.
Double Tap โค๏ธ For Part-8
โค9๐1
Which Python data structure is ordered, mutable, and allows duplicate values?
Anonymous Quiz
9%
A) Set
23%
B) Tuple
60%
C) List
9%
D) Dictionary
๐2โค1
Which data structure stores only unique elements?
Anonymous Quiz
8%
A) List
26%
B) Tuple
46%
C) Set
20%
D) Dictionary
๐2โค1
Which statement about tuples is correct?
Anonymous Quiz
12%
A) Tuples are mutable.
23%
B) Tuples do not allow duplicate values.
61%
C) Tuples are immutable.
4%
D) Tuples are unordered.
โค5
What will be the output of the following code?
numbers = {1, 2, 2, 3, 4, 4}
print(len(numbers))
numbers = {1, 2, 2, 3, 4, 4}
print(len(numbers))
Anonymous Quiz
35%
4
14%
5
50%
6
1%
7
โค6
๐๐ & ๐๐ฎ๐๐ฎ ๐ฆ๐ฐ๐ถ๐ฒ๐ป๐ฐ๐ฒ ๐ฃ๐ฟ๐ผ๐ด๐ฟ๐ฎ๐บ (๐ก๐ผ ๐๐ผ๐ฑ๐ถ๐ป๐ด ๐ก๐ฒ๐ฒ๐ฑ๐ฒ๐ฑ)
Apply Now๐:- https://pdlink.in/4aYWald
By E&ICT Academy, IIT Roorkee
Batch Closing Soon - 26th July 2026
Apply Now๐:- https://pdlink.in/4aYWald
By E&ICT Academy, IIT Roorkee
Batch Closing Soon - 26th July 2026
๐ Data Science Roadmap 2026
๐ Phase 1: Programming Fundamentals
๐ Topic 8: Python List Comprehensions
Welcome back! ๐
In the previous lesson, you learned about Python's built-in data structuresโLists, Tuples, Sets, and Dictionaries.
Now it's time to learn one of Python's most elegant and frequently used features: List Comprehensions.
List comprehensions provide a concise and readable way to create, filter, and transform lists. They are widely used in Data Science, Machine Learning, data preprocessing, and coding interviews.
๐น 1. What is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable (such as a list, tuple, or range).
Instead of writing multiple lines with a loop, you can accomplish the same task in a single line.
General Syntax
๐น 2. Creating a List Using a Loop
Output
๐น 3. Creating the Same List Using List Comprehension
Output
Notice how the code is shorter and easier to read.
๐น 4. Performing Calculations
Create a list of squares.
Output
๐น 5. Using Conditions
You can filter elements while creating a list.
Example: Even Numbers
Output
๐น 6. Converting Strings
Convert all names to uppercase.
Output
๐น 7. Using Conditional Expressions
Replace negative numbers with zero.
Output
๐น 8. Nested List Comprehension
Create a multiplication table.
Output
๐น 9. Real-World Data Science Example
Suppose you have a list of sales amounts.
Output
This technique is commonly used while cleaning and filtering datasets before analysis.
๐น 10. Benefits of List Comprehensions
โ Shorter code
โ Easier to read
โ Faster than traditional loops in many cases
โ Widely used in Data Science and Machine Learning
๐น 11. Common Mistakes
โ Forgetting the Expression
Correct:
โ Incorrect Order of "if"
Correct:
๐ Phase 1: Programming Fundamentals
๐ Topic 8: Python List Comprehensions
Welcome back! ๐
In the previous lesson, you learned about Python's built-in data structuresโLists, Tuples, Sets, and Dictionaries.
Now it's time to learn one of Python's most elegant and frequently used features: List Comprehensions.
List comprehensions provide a concise and readable way to create, filter, and transform lists. They are widely used in Data Science, Machine Learning, data preprocessing, and coding interviews.
๐น 1. What is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable (such as a list, tuple, or range).
Instead of writing multiple lines with a loop, you can accomplish the same task in a single line.
General Syntax
new_list = [expression for item in iterable]๐น 2. Creating a List Using a Loop
numbers = []
for i in range(5):
numbers.append(i)
print(numbers)
Output
[0, 1, 2, 3, 4]
๐น 3. Creating the Same List Using List Comprehension
numbers = [i for i in range(5)]
print(numbers)
Output
[0, 1, 2, 3, 4]
Notice how the code is shorter and easier to read.
๐น 4. Performing Calculations
Create a list of squares.
squares = [x ** 2 for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]
๐น 5. Using Conditions
You can filter elements while creating a list.
Example: Even Numbers
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)
Output
[2, 4, 6, 8, 10]
๐น 6. Converting Strings
Convert all names to uppercase.
names = ["rahul", "deepak", "anita"]
upper_names = [name.upper() for name in names]
print(upper_names)
Output
['RAHUL', 'DEEPAK', 'ANITA']
๐น 7. Using Conditional Expressions
Replace negative numbers with zero.
numbers = [5, -2, 8, -1, 3]
updated = [0 if x < 0 else x for x in numbers]
print(updated)
Output
[5, 0, 8, 0, 3]
๐น 8. Nested List Comprehension
Create a multiplication table.
table = [[i * j for j in range(1, 6)] for i in range(1, 4)]
print(table)
Output
[[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15]]
๐น 9. Real-World Data Science Example
Suppose you have a list of sales amounts.
sales = [1200, 850, 1500, 600, 2000]
high_sales = [sale for sale in sales if sale > 1000]
print(high_sales)
Output
[1200, 1500, 2000]
This technique is commonly used while cleaning and filtering datasets before analysis.
๐น 10. Benefits of List Comprehensions
โ Shorter code
โ Easier to read
โ Faster than traditional loops in many cases
โ Widely used in Data Science and Machine Learning
๐น 11. Common Mistakes
โ Forgetting the Expression
numbers = [for i in range(5)] # SyntaxError
Correct:
numbers = [i for i in range(5)]
โ Incorrect Order of "if"
numbers = [if x % 2 == 0 x for x in range(10)] # SyntaxError
Correct:
numbers = [x for x in range(10) if x % 2 == 0]
โค9๐1
๐ฏ Practice Questions
1. Create a list of numbers from 1 to 20.
2. Create a list containing the squares of numbers from 1 to 10.
3. Create a list containing only odd numbers from 1 to 20.
4. Convert a list of names to lowercase.
5. Replace all negative values in a list with zero using a list comprehension.
๐ฏ Key Takeaways
โ List comprehensions provide a concise way to create lists.
โ They combine loops and expressions into a single line.
โ You can filter data using "if" conditions.
โ Conditional expressions allow values to be modified during list creation.
โ List comprehensions are widely used in data cleaning, feature engineering, and machine learning workflows.
Mastering list comprehensions will help you write cleaner, more Pythonic code and prepare you for technical interviews and real-world Data Science projects.
Double Tap โค๏ธ For Part-9
1. Create a list of numbers from 1 to 20.
2. Create a list containing the squares of numbers from 1 to 10.
3. Create a list containing only odd numbers from 1 to 20.
4. Convert a list of names to lowercase.
5. Replace all negative values in a list with zero using a list comprehension.
๐ฏ Key Takeaways
โ List comprehensions provide a concise way to create lists.
โ They combine loops and expressions into a single line.
โ You can filter data using "if" conditions.
โ Conditional expressions allow values to be modified during list creation.
โ List comprehensions are widely used in data cleaning, feature engineering, and machine learning workflows.
Mastering list comprehensions will help you write cleaner, more Pythonic code and prepare you for technical interviews and real-world Data Science projects.
Double Tap โค๏ธ For Part-9
โค9
๐ Data Science Roadmap 2026
๐ Phase 1: Programming Fundamentals
๐ Topic 8: Python List Comprehensions
Welcome back! ๐
In the previous lesson, you learned about Python's built-in data structuresโLists, Tuples, Sets, and Dictionaries.
Now it's time to learn one of Python's most elegant and frequently used features: List Comprehensions.
List comprehensions provide a concise and readable way to create, filter, and transform lists. They are widely used in Data Science, Machine Learning, data preprocessing, and coding interviews.
๐น 1. What is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable (such as a list, tuple, or range).
Instead of writing multiple lines with a loop, you can accomplish the same task in a single line.
General Syntax
๐น 2. Creating a List Using a Loop
Output
๐น 3. Creating the Same List Using List Comprehension
Output
Notice how the code is shorter and easier to read.
๐น 4. Performing Calculations
Create a list of squares.
Output
๐น 5. Using Conditions
You can filter elements while creating a list.
Example: Even Numbers
Output
๐น 6. Converting Strings
Convert all names to uppercase.
Output
๐น 7. Using Conditional Expressions
Replace negative numbers with zero.
Output
๐น 8. Nested List Comprehension
Create a multiplication table.
Output
๐น 9. Real-World Data Science Example
Suppose you have a list of sales amounts.
๐ Phase 1: Programming Fundamentals
๐ Topic 8: Python List Comprehensions
Welcome back! ๐
In the previous lesson, you learned about Python's built-in data structuresโLists, Tuples, Sets, and Dictionaries.
Now it's time to learn one of Python's most elegant and frequently used features: List Comprehensions.
List comprehensions provide a concise and readable way to create, filter, and transform lists. They are widely used in Data Science, Machine Learning, data preprocessing, and coding interviews.
๐น 1. What is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable (such as a list, tuple, or range).
Instead of writing multiple lines with a loop, you can accomplish the same task in a single line.
General Syntax
new_list = [expression for item in iterable]๐น 2. Creating a List Using a Loop
numbers = []
for i in range(5):
numbers.append(i)
print(numbers)
Output
[0, 1, 2, 3, 4]๐น 3. Creating the Same List Using List Comprehension
numbers = [i for i in range(5)]
print(numbers)
Output
[0, 1, 2, 3, 4] Notice how the code is shorter and easier to read.
๐น 4. Performing Calculations
Create a list of squares.
squares = [x ** 2 for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]๐น 5. Using Conditions
You can filter elements while creating a list.
Example: Even Numbers
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)
Output
[2, 4, 6, 8, 10]๐น 6. Converting Strings
Convert all names to uppercase.
names = ["rahul", "deepak", "anita"]
upper_names = [name.upper() for name in names]
print(upper_names)
Output
['RAHUL', 'DEEPAK', 'ANITA']๐น 7. Using Conditional Expressions
Replace negative numbers with zero.
numbers = [5, -2, 8, -1, 3]
updated = [0 if x < 0 else x for x in numbers]
print(updated)
Output
[5, 0, 8, 0, 3]๐น 8. Nested List Comprehension
Create a multiplication table.
table = [[i * j for j in range(1, 6)] for i in range(1, 4)]
print(table)
Output
[[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15]]
๐น 9. Real-World Data Science Example
Suppose you have a list of sales amounts.
sales = [1200, 850, 1500, 600, 2000]
high_sales = [sale for sale in sales if sale > 1000]
print(high_sales)
โค5
Output
This technique is commonly used while cleaning and filtering datasets before analysis.
๐น 10. Benefits of List Comprehensions
โ Shorter code
โ Easier to read
โ Faster than traditional loops in many cases
โ Widely used in Data Science and Machine Learning
๐น 11. Common Mistakes
โ Forgetting the Expression
Correct:
โ Incorrect Order of "if"
Correct:
๐ฏ Practice Questions
1. Create a list of numbers from 1 to 20.
2. Create a list containing the squares of numbers from 1 to 10.
3. Create a list containing only odd numbers from 1 to 20.
4. Convert a list of names to lowercase.
5. Replace all negative values in a list with zero using a list comprehension.
๐ฏ Key Takeaways
โ List comprehensions provide a concise way to create lists.
โ They combine loops and expressions into a single line.
โ You can filter data using "if" conditions.
โ Conditional expressions allow values to be modified during list creation.
โ List comprehensions are widely used in data cleaning, feature engineering, and machine learning workflows.
Mastering list comprehensions will help you write cleaner, more Pythonic code and prepare you for technical interviews and real-world Data Science projects.
Double Tap โค๏ธ For Part-9
[1200, 1500, 2000] This technique is commonly used while cleaning and filtering datasets before analysis.
๐น 10. Benefits of List Comprehensions
โ Shorter code
โ Easier to read
โ Faster than traditional loops in many cases
โ Widely used in Data Science and Machine Learning
๐น 11. Common Mistakes
โ Forgetting the Expression
numbers = [for i in range(5)] # SyntaxErrorCorrect:
numbers = [i for i in range(5)]โ Incorrect Order of "if"
numbers = [if x % 2 == 0 x for x in range(10)]Correct:
numbers = [x for x in range(10) if x % 2 == 0]๐ฏ Practice Questions
1. Create a list of numbers from 1 to 20.
2. Create a list containing the squares of numbers from 1 to 10.
3. Create a list containing only odd numbers from 1 to 20.
4. Convert a list of names to lowercase.
5. Replace all negative values in a list with zero using a list comprehension.
๐ฏ Key Takeaways
โ List comprehensions provide a concise way to create lists.
โ They combine loops and expressions into a single line.
โ You can filter data using "if" conditions.
โ Conditional expressions allow values to be modified during list creation.
โ List comprehensions are widely used in data cleaning, feature engineering, and machine learning workflows.
Mastering list comprehensions will help you write cleaner, more Pythonic code and prepare you for technical interviews and real-world Data Science projects.
Double Tap โค๏ธ For Part-9
โค10
๐ฐ India needs 10 lakh+ AI/ML professionals by end of 2026.
Half those roles canโt find qualified candidates.
Thatโs not a job market. Thatโs an open goal.
Certification in AI & ML - Vishlesan i-Hub, IIT Patna
โ Scikit-learn โ PyTorch โ Transformers โ RAG & Agents
โ Deploy models with FastAPI, Docker & MLOps
โ Live learning from IIT faculty & industry mentors
โ Placement support through Masai's network of 5000+ companies
The qualifier is this Sunday. One attempt.
๐ โน99 Test - 2nd August
๐ https://tinyurl.com/DS-29JUL-006
Half those roles canโt find qualified candidates.
Thatโs not a job market. Thatโs an open goal.
Certification in AI & ML - Vishlesan i-Hub, IIT Patna
โ Scikit-learn โ PyTorch โ Transformers โ RAG & Agents
โ Deploy models with FastAPI, Docker & MLOps
โ Live learning from IIT faculty & industry mentors
โ Placement support through Masai's network of 5000+ companies
The qualifier is this Sunday. One attempt.
๐ โน99 Test - 2nd August
๐ https://tinyurl.com/DS-29JUL-006
โค4
๐ Data Science Roadmap 2026
๐ Phase 1: Programming Fundamentals
๐ Topic 9: Python Lambda Functions, map(), filter(), and reduce()
Welcome back! ๐
So far, you've learned Python basics, loops, functions, data structures, and list comprehensions. In this lesson, you'll learn functional programming concepts in Python using Lambda Functions, map(), filter(), and reduce().
These are widely used in Data Science for transforming, filtering, and processing large datasets efficiently.
๐น 1. What is a Lambda Function?
A Lambda Function is a small anonymous function that can have any number of arguments but only one expression.
Unlike normal functions, lambda functions don't require a name.
Syntax
Example
Output:
This is equivalent to:
๐น 2. Why Use Lambda Functions?
Lambda functions are useful when:
โ You need a simple function only once.
โ You want shorter, cleaner code.
โ You're using functions like map(), filter(), or sorted().
๐น 3. Lambda with Multiple Arguments
Output:
๐น 4. The map() Function
The map() function applies a function to every item in an iterable.
Syntax:
Example
Output:
๐น 5. Using map() with a Normal Function
Output:
๐น 6. The filter() Function
The filter() function selects only those elements that satisfy a condition.
Syntax:
Example
Output:
๐น 7. The reduce() Function
The reduce() function applies a function repeatedly to reduce an iterable to a single value.
It is available in the
Output:
๐น 8. Difference Between map(), filter(), and reduce()
map(): Transforms every element in an iterable and returns a new iterable.
filter(): Keeps only elements that match a condition and returns a filtered iterable.
reduce(): Combines all elements into a single value.
๐น 9. Real-World Data Science Example
Suppose you have customer purchase amounts.
Output:
Now calculate the total revenue.
Output:
๐น 10. Combining map() and filter()
๐ Phase 1: Programming Fundamentals
๐ Topic 9: Python Lambda Functions, map(), filter(), and reduce()
Welcome back! ๐
So far, you've learned Python basics, loops, functions, data structures, and list comprehensions. In this lesson, you'll learn functional programming concepts in Python using Lambda Functions, map(), filter(), and reduce().
These are widely used in Data Science for transforming, filtering, and processing large datasets efficiently.
๐น 1. What is a Lambda Function?
A Lambda Function is a small anonymous function that can have any number of arguments but only one expression.
Unlike normal functions, lambda functions don't require a name.
Syntax
lambda arguments: expressionExample
square = lambda x: x * x
print(square(5))
Output:
25This is equivalent to:
def square(x):
return x * x
๐น 2. Why Use Lambda Functions?
Lambda functions are useful when:
โ You need a simple function only once.
โ You want shorter, cleaner code.
โ You're using functions like map(), filter(), or sorted().
๐น 3. Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Output:
30๐น 4. The map() Function
The map() function applies a function to every item in an iterable.
Syntax:
map(function, iterable)Example
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
Output:
[1, 4, 9, 16, 25]๐น 5. Using map() with a Normal Function
def double(x):
return x * 2
numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result)
Output:
[2, 4, 6, 8]๐น 6. The filter() Function
The filter() function selects only those elements that satisfy a condition.
Syntax:
filter(function, iterable)Example
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4, 6]๐น 7. The reduce() Function
The reduce() function applies a function repeatedly to reduce an iterable to a single value.
It is available in the
functools module.from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda a, b: a + b, numbers)
print(result)
Output:
10๐น 8. Difference Between map(), filter(), and reduce()
map(): Transforms every element in an iterable and returns a new iterable.
filter(): Keeps only elements that match a condition and returns a filtered iterable.
reduce(): Combines all elements into a single value.
๐น 9. Real-World Data Science Example
Suppose you have customer purchase amounts.
purchases = [1200, 450, 1800, 900, 2500]
high_value = list(filter(lambda x: x > 1000, purchases))
print(high_value)
Output:
[1200, 1800, 2500]Now calculate the total revenue.
from functools import reduce
total = reduce(lambda a, b: a + b, purchases)
print(total)
Output:
6850๐น 10. Combining map() and filter()
numbers = [1, 2, 3, 4, 5, 6]
result = list(
map(
lambda x: x * 10,
filter(lambda x: x % 2 == 0, numbers)
)
)
print(result)
โค5
Output:
First, filter() keeps only even numbers.
Then, map() multiplies each by 10.
๐น 11. Common Mistakes
โ Forgetting to Convert map() to a List
โ
Correct:
โ Forgetting to Import reduce()
โ
Correct:
๐ฏ Practice Questions
1. Create a lambda function that returns the cube of a number.
2. Use map() to convert a list of temperatures from Celsius to Fahrenheit.
3. Use filter() to find numbers greater than 50.
4. Use reduce() to calculate the product of a list of numbers.
5. Combine filter() and map() to square only the odd numbers in a list.
๐ฏ Key Takeaways
โ Lambda functions are short, anonymous functions.
โ map() transforms every element in an iterable.
โ filter() selects elements based on a condition.
โ reduce() combines all elements into a single value.
โ These functions are widely used for data transformation, preprocessing, and feature engineering in Data Science.
Double Tap โค๏ธ For More
[20, 40, 60]
First, filter() keeps only even numbers.
Then, map() multiplies each by 10.
๐น 11. Common Mistakes
โ Forgetting to Convert map() to a List
result = map(lambda x: x * 2, numbers)
โ
<map object at ...>
Correct:
print(list(result))
โ Forgetting to Import reduce()
result = reduce(lambda a, b: a + b, [1, 2, 3])
โ
NameError
Correct:
from functools import reduce
๐ฏ Practice Questions
1. Create a lambda function that returns the cube of a number.
2. Use map() to convert a list of temperatures from Celsius to Fahrenheit.
3. Use filter() to find numbers greater than 50.
4. Use reduce() to calculate the product of a list of numbers.
5. Combine filter() and map() to square only the odd numbers in a list.
๐ฏ Key Takeaways
โ Lambda functions are short, anonymous functions.
โ map() transforms every element in an iterable.
โ filter() selects elements based on a condition.
โ reduce() combines all elements into a single value.
โ These functions are widely used for data transformation, preprocessing, and feature engineering in Data Science.
Double Tap โค๏ธ For More
โค8