Skip to content

Functions and Lambdas in Python

Introduction to Functions

Title Concept Codes
What are Functions? Blocks of reusable code that perform a specific task. Encapsulate logic, promote code reuse, and enhance code modularity.
Function Syntax in Python Define functions, arguments, and return values in Python. Functions are defined using the def keyword with optional parameters and return statements.
Purpose of Functions Modularity, Reusability, and Improved Code Organization. Functions break down complex systems into manageable components and streamline code maintenance.

1. Defining Functions

  1. Function Syntax:

    def my_function(param1, param2):
        # Function code here
        return result
    

  2. Function Arguments:

  3. Positional Arguments
  4. Keyword Arguments
  5. Default Arguments
  6. Variable-Length Arguments

  7. Function Returns:

  8. Optional return statement
  9. Can return single or multiple values

Working with Functions

Function Parameters

Title Concept Codes
Positional Parameters Arguments passed based on order. def greet(name, message):
    print(f"Hello, {name}! {message}")
Keyword Parameters Arguments passed based on names provided. greet(message="How are you?", name="Alice")
Default Parameters Predefined values for function arguments. def greet(name, message="Good day!"):
    print(f"Hello, {name}! {message}")
Variable-Length Arguments Handle arbitrary number of arguments. def sum_values(*args):
    return sum(args)

Function Scope

Title Concept Codes
Global vs. Local Scope Differentiating variable accessibility within functions. Global variables accessible throughout, local variables limited to function scope.
Accessing Variables in Different Scopes Utilizing variables with specific scopes. global_var = 10
def my_func():
    local_var = 5
The 'global' Keyword Modifying global variables within function scope. def change_global_value():
    global global_var
    global_var = 20

Lambda Functions

Title Concept Codes
Definition and Syntax Anonymous functions defined in a single line. lambda x, y: x + y
Advantages of Lambda Functions Concise, no need for def keyword, used for short functions. lambda x: x**2 if x > 0 else 0
Use Cases for Lambda Functions Functional programming, data transformations, quick functions. list(map(lambda x: x+2, [1, 2, 3]))

Built-in Functions in Python

Common Built-in Functions

  1. print() Function
  2. len() Function
  3. range() Function

map() Function

  1. Using map() with Functions

    numbers = [1, 2, 3]
    squared = list(map(lambda x: x**2, numbers))
    

  2. Lambda Functions with map()

    names = ['Alice', 'Bob', 'Charlie']
    lengths = list(map(lambda x: len(x), names))
    

filter() Function

  1. Using filter() with Functions

    numbers = [1, 2, 3, 4, 5]
    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
    

  2. Lambda Functions with filter()

    names = ['Alice', 'Bob', 'Charlie']
    long_names = list(filter(lambda x: len(x) > 5, names))
    

Recursion in Python

Understanding Recursion

  1. Definition and Concepts
  2. A function calling itself
  3. Breaks a problem into smaller, similar subproblems

  4. Recursive Functions

  5. Must have a base case to terminate
  6. Examples: Factorial, Fibonacci

Advantages and Limitations

  1. Pros of Recursion
  2. Elegant solutions for some problems
  3. Improves readability for certain algorithms

  4. Common Pitfalls and Limitations

  5. Stack overflow with excessive recursion
  6. Harder to debug compared to iterative solutions

Recursive Examples

  1. Writing Recursive Functions

    def factorial(n):
        if n == 1:
            return 1
        else:
            return n * factorial(n - 1)
    

  2. Recursion vs. Iteration

  3. Recursion: Compact and elegant
  4. Iteration: Better for performance in some cases

Functional Programming Concepts

Pure Functions

  1. Definition and Characteristics
  2. Output solely determined by input
  3. No side effects

  4. Benefits of Pure Functions

  5. Easier to test and debug
  6. Enables parallel and concurrent execution

Higher-Order Functions

  1. Definition and Examples
  2. Functions that take other functions as arguments
  3. Examples: map(), filter()

  4. Using Functions as Parameters

  5. Enhances code reusability and flexibility
  6. Example: sorted()

Immutability and Higher-Order Functions

  1. Understanding Immutability
  2. Data that cannot be changed after creation
  3. Promotes functional programming principles

  4. Applying Higher-Order Functions with Immutable Data

  5. Avoids unintended data changes
  6. Supports functional programming paradigms