Python Programming

Python Lambda Functions, List Comprehensions, and Modules

Introduction

As Python programs become larger, we need:

  • Short functions for simple tasks
  • Faster ways to create lists
  • Better code organization
  • Reusable code across multiple files

Python provides:

  1. Lambda Functions
  2. List Comprehensions
  3. Modules
  4. Import Statements

These concepts are heavily used in:

  • Automation
  • Django
  • Flask
  • Data Science
  • Machine Learning
  • Real-world Applications

Anonymous (Lambda) Function

What is a Lambda Function?

A lambda function is a small anonymous function.

Anonymous means:

Function without a name

Normal functions use:

def

Lambda functions use:

lambda

Why Use Lambda?

Useful when:

  • Function is very small
  • Used only once
  • Passed to another function
  • Sorting data
  • Filtering data
  • Data processing

Syntax

lambda parameters: expression

Structure:

lambda
   ↓
parameters
   ↓
expression

Normal Function Example

def square(n):
    return n * n

print(square(5))

Output:

25

Lambda Version

square = lambda n: n * n

print(square(5))

Output:

25

Multiple Parameters

add = lambda a, b: a + b

print(add(10, 20))

Output:

30

Three Parameters

total = lambda a, b, c: a + b + c

print(total(10, 20, 30))

Output:

60

Lambda Returning Boolean

is_even = lambda n: n % 2 == 0

print(is_even(10))

Output:

True

Lambda with String

greet = lambda name: "Hello " + name

print(greet("Rahul"))

Output:

Hello Rahul

Lambda vs Normal Function

Normal Function Lambda Function
Uses def Uses lambda
Can contain many statements Only one expression
Can have multiple lines Single line
Easier for complex logic Best for simple logic

Limitations of Lambda

Lambda can contain only:

One Expression

Invalid Lambda

❌ Wrong

lambda x:

    y = x + 1

    return y

Correct

lambda x: x + 1

Common Lambda Mistakes


Mistake 1

Using Lambda for Large Logic

❌ Bad

lambda x: complicated_program

Use normal functions instead.


Mistake 2

Trying to Use Multiple Statements

❌ Wrong

lambda x:

    print(x)

    return x

Mistake 3

Forgetting Assignment

❌ Wrong

lambda x: x * x

Function created but not stored.


✅ Correct

square = lambda x: x * x

List Comprehension

What is List Comprehension?

List comprehension provides a shorter way to create lists.

Without list comprehension:

numbers = []

for i in range(5):
    numbers.append(i)

print(numbers)

Output:

[0, 1, 2, 3, 4]

List Comprehension Version

numbers = [i for i in range(5)]

print(numbers)

Output:

[0, 1, 2, 3, 4]

Syntax

[expression for item in iterable]

Visual Representation

Expression
     ↓

for item in iterable

     ↓

Create List

Example 1

numbers = [x for x in range(1, 6)]

print(numbers)

Output:

[1, 2, 3, 4, 5]

Example 2: Squares

Without comprehension:

result = []

for i in range(1, 6):
    result.append(i * i)

Using comprehension:

result = [i * i for i in range(1, 6)]

print(result)

Output:

[1, 4, 9, 16, 25]

Example 3: Cubes

cubes = [i ** 3 for i in range(1, 6)]

print(cubes)

Output:

[1, 8, 27, 64, 125]

Conditional List Comprehension

Syntax:

[expression for item in iterable if condition]

Example: Even Numbers

evens = [i for i in range(10) if i % 2 == 0]

print(evens)

Output:

[0, 2, 4, 6, 8]

Example: Odd Numbers

odds = [i for i in range(10) if i % 2 != 0]

print(odds)

Output:

[1, 3, 5, 7, 9]

Example: Uppercase Strings

names = ["john", "alice", "bob"]

result = [name.upper() for name in names]

print(result)

Output:

['JOHN', 'ALICE', 'BOB']

Nested List Comprehension

pairs = [(x, y)
         for x in range(3)
         for y in range(3)]

print(pairs)

Output:

[(0,0), (0,1), (0,2),
 (1,0), (1,1), (1,2),
 (2,0), (2,1), (2,2)]

Common List Comprehension Mistakes


Mistake 1

Using Parentheses Instead of Brackets

❌ Wrong

numbers = (x for x in range(5))

Creates generator, not list.


Mistake 2

Wrong Order

❌ Wrong

[i if i % 2 == 0 for i in range(10)]

✅ Correct

[i for i in range(10) if i % 2 == 0]

Mistake 3

Making Comprehensions Too Complex

Avoid very long comprehensions.

Use loops when readability suffers.


What is a Module?

A module is a Python file containing code.

Example:

calculator.py

Anything saved inside:

calculator.py

becomes a module.


Why Use Modules?

Benefits:

  • Code Reusability
  • Better Organization
  • Easier Maintenance
  • Less Duplication
  • Cleaner Projects

Defining a Module

A module is simply:

A Python file (.py)

Example:

math_tools.py

Create Your First Module

Create file:

calculator.py

Content:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Save the file.

You have created a module.


Project Structure

project/

│
├── calculator.py
└── main.py

Importing Module

Import Entire Module

main.py

import calculator

print(calculator.add(10, 20))

print(calculator.subtract(30, 5))

Output:

30
25

How It Works

main.py
     ↓
imports
     ↓
calculator.py
     ↓
uses functions

Example with More Functions

calculator.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

main.py

import calculator

print(calculator.add(10, 5))

print(calculator.multiply(10, 5))

print(calculator.divide(20, 4))

Output:

15
50
5.0

Import Specific Function

Instead of importing everything:

from calculator import add

Example:

from calculator import add

print(add(10, 20))

Output:

30

Import Multiple Functions

from calculator import add, subtract

Example:

print(add(10, 20))

print(subtract(20, 10))

Import All Functions

from calculator import *

Example:

print(add(5, 5))

print(subtract(10, 3))

⚠ Generally not recommended.

Reason:

Namespace pollution

Import with Alias

import calculator as calc

Example:

print(calc.add(10, 20))

Output:

30

Function Call from Imported Module

Example:

calculator.py

def square(n):
    return n * n

main.py

import calculator

print(calculator.square(5))

Output:

25

Built-in Modules

Python already provides many modules.

Examples:

Module Purpose
math Mathematical operations
random Random numbers
datetime Date and time
os Operating system
sys System information

Example: math Module

import math

print(math.sqrt(25))

Output:

5.0

Example: random Module

import random

print(random.randint(1, 10))

Possible Output:

7

Common Module Mistakes


Mistake 1

Wrong File Name

Calculator.py

Importing:

import calculator

May fail depending on OS.


Mistake 2

Misspelling Function Name

calculator.ad()

Output:

AttributeError

Mistake 3

Forgetting Module Prefix

import calculator

add(10, 20)

Output:

NameError

✅ Correct

calculator.add(10, 20)

Mistake 4

Circular Imports

Avoid:

A imports B

B imports A

Homework 1

Create a lambda function that doubles a number.


Solution

double = lambda x: x * 2

print(double(10))

Output:

20

Homework 2

Create a lambda function to find the larger number.


Solution

largest = lambda a, b: a if a > b else b

print(largest(10, 20))

Output:

20

Homework 3

Create a list of squares from 1 to 10 using list comprehension.


Solution

squares = [i * i for i in range(1, 11)]

print(squares)

Homework 4

Create a list of even numbers from 1 to 50.


Solution

evens = [i for i in range(1, 51)
         if i % 2 == 0]

print(evens)

Homework 5

Create a module named calculator.py with:

  • add
  • subtract

functions.

Use them in main.py.


Solution

calculator.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

main.py

import calculator

print(calculator.add(10, 20))

print(calculator.subtract(20, 5))

Output:

30
15

Homework 6

Import add() only from calculator.py.


Solution

from calculator import add

print(add(10, 20))

Output:

30

Homework 7

Import calculator module using alias.


Solution

import calculator as calc

print(calc.add(5, 5))

Output:

10

Quick Revision

Topic Description
Lambda Function Anonymous function
lambda Creates anonymous function
List Comprehension Short way to create lists
Module Python file
import Imports module
from module import Imports specific item
Alias Alternate module name
Built-in Module Module provided by Python

Summary

Concept Key Point
Lambda Function Small one-line function
List Comprehension Compact list creation
Module Reusable Python file
Import Access code from another file
Alias Short module name
Built-in Modules math, random, os, datetime
User Module Created by programmer
Reusability Major benefit of modules

Before moving to the next chapter, make sure you can:

✅ Write lambda functions

✅ Convert loops into list comprehensions

✅ Create your own module

✅ Import modules correctly

✅ Use aliases

✅ Create multi-function modules

✅ Build a calculator module and use it from another file

Filters

No filters available for this view.

Reset All