2.
List Comprehensions
Introduction
List comprehension is an easy and short method used to create lists in Python.
Instead of writing many lines using loops, we can create lists in a single line.
It makes the program simple, readable, and faster.
List comprehension is mainly used in data science for filtering
and modifying data.
Syntax
[expression for item in iterable]
Example 1: Creating a List
nums = [x for x in range(5)]
print(nums)
Theory
This program creates a list of numbers from 0 to 4 using list comprehension.
Output
[0, 1, 2, 3, 4]
Example 2: Square of Numbers
square = [x*x for x in range(5)]
print(square)
Theory
This program calculates the square of each number from 0 to 4 and stores them in a list.
Output
[0, 1, 4, 9, 16]
Example 3: Using Condition
even = [x for x in range(10) if x % 2 == 0]
print(even)
Theory
This program checks numbers from 0 to 9 and stores only even numbers in the list.
Output
[0, 2, 4, 6, 8]
Advantages of List Comprehension
• Reduces code length
• Improves readability
• Faster execution
• Easy data filtering
Applications in Data Science
• Data cleaning
• Data filtering
• Transforming datasets
• Removing unwanted values
Conclusion
List comprehension is a useful Python feature for creating and
managing lists easily.
It saves time, reduces code complexity, and is widely used in Python and data science
applications.
3. Lambda Functions
Introduction
Lambda function is a small anonymous function in Python. It is called an anonymous
function because it does not have a function name.
Lambda functions are used for simple operations and reduce the
number of lines in a program.
They are commonly used in data science for filtering, sorting,
and transforming data.
Syntax
lambda arguments : expression
Example 1: Addition of Two Numbers
add = lambda a, b: a + b
print(add(2,3))
Theory
This program uses a lambda function to add two numbers and
display the result.
Output
Example 2: Square of a Number
square = lambda x: x*x
print(square(4))
Theory
This program calculates the square of a number using a lambda
function.
Output
16
Example 3: Using Lambda with map()
nums = [1,2,3,4]
result = list(map(lambda x: x*2, nums))
print(result)
Theory
This program multiplies each number in the list by 2 using lambda
function and map().
Output
[2, 4, 6, 8]
Example 4: Using Lambda with filter()
nums = [1,2,3,4,5,6]
even = list(filter(lambda x: x%2==0, nums))
print(even)
Theory
This program filters only even numbers from the list using lambda
function.
Output
[2, 4, 6]
Advantages of Lambda Functions
• Reduces code size
• Easy to write simple functions
• Improves readability
• Useful with map() and filter()
Applications in Data Science
• Data filtering
• Data transformation
• Sorting datasets
• Mathematical calculations
Conclusion
Lambda functions are simple and efficient functions in Python
used for short operations. They help reduce code complexity and
are widely used in data science and data processing applications.