Python Functions: Built-in, User-Defined & Lambda

Master Python functions! Explore built-in, user-defined (`def`), and lambda functions for efficient AI/ML development and data science.

Python Functions

This document provides a comprehensive overview of functions in Python, covering built-in functions, user-defined functions using def, and anonymous functions (lambda functions).

4.1 Python Built-in Functions

Python provides a rich set of built-in functions that are readily available for immediate use without the need for importing any modules. These functions perform common tasks such as type conversions, mathematical operations, input/output, and more.

Here are some of the most commonly used built-in functions:

  • print(): Displays output to the console.

    print("Hello, world!")
  • len(): Returns the length (number of items) of an object.

    my_list = [1, 2, 3, 4, 5]
    print(len(my_list))  # Output: 5
  • type(): Returns the type of an object.

    x = 10
    print(type(x))  # Output: <class 'int'>
  • int(), float(), str(), list(), tuple(), dict(), set(): These are type conversion functions.

    num_str = "123"
    num_int = int(num_str)
    print(num_int)  # Output: 123
    
    num = 45.67
    num_str_float = str(num)
    print(num_str_float)  # Output: 45.67
  • input(): Prompts the user for input and returns it as a string.

    name = input("Enter your name: ")
    print("Hello, " + name + "!")
  • max(), min(): Returns the largest or smallest item in an iterable or the largest/smallest of two or more arguments.

    numbers = [10, 5, 20, 15]
    print(max(numbers))  # Output: 20
    print(min(numbers))  # Output: 5
  • sum(): Calculates the sum of all items in an iterable.

    numbers = [1, 2, 3, 4]
    print(sum(numbers))  # Output: 10
  • round(): Rounds a number to a specified number of decimal places.

    pi = 3.14159
    print(round(pi, 2))  # Output: 3.14
  • abs(): Returns the absolute value of a number.

    negative_num = -15
    print(abs(negative_num))  # Output: 15

This is not an exhaustive list, but covers many of the frequently used built-in functions.

4.2 def Functions (User-Defined Functions)

User-defined functions are blocks of reusable code that perform a specific task. They are created using the def keyword. Defining functions helps in organizing code, promoting reusability, and making programs more modular and readable.

Syntax:

def function_name(parameters):
    """Docstring: Explains what the function does."""
    # Function body: statements to perform the task
    # ...
    return expression  # Optional: returns a value from the function
  • def: Keyword to declare a function.
  • function_name: A descriptive name for the function.
  • parameters: (Optional) Variables that accept input values when the function is called.
  • Docstring: A string literal used to document the function's purpose, arguments, and return values. It's good practice to include docstrings.
  • Function body: The indented block of code that executes when the function is called.
  • return: (Optional) Used to send a value back from the function to the caller. If return is omitted, the function implicitly returns None.

Example 1: A simple function with no arguments and no return value.

def greet():
    """This function prints a simple greeting."""
    print("Hello there!")

# Calling the function
greet()

Example 2: A function with arguments.

def greet_person(name):
    """This function greets a person by name."""
    print(f"Hello, {name}!")

# Calling the function with an argument
greet_person("Alice")

Example 3: A function with arguments and a return value.

def add_numbers(a, b):
    """This function takes two numbers and returns their sum."""
    result = a + b
    return result

# Calling the function and storing the returned value
sum_result = add_numbers(5, 3)
print(f"The sum is: {sum_result}")

Example 4: Functions with default argument values.

Default argument values allow you to assign a default value to a parameter. If the argument is not provided when the function is called, the default value is used.

def power(base, exponent=2):
    """Calculates base raised to the power of exponent."""
    return base ** exponent

# Calling with both arguments
print(power(3, 3))  # Output: 27

# Calling with only the base (exponent defaults to 2)
print(power(4))     # Output: 16

Example 5: Functions with variable-length arguments (*args and **kwargs).

  • *args: Allows a function to accept an arbitrary number of positional arguments. These arguments are passed as a tuple.
  • **kwargs: Allows a function to accept an arbitrary number of keyword arguments. These arguments are passed as a dictionary.
def process_items(*args, **kwargs):
    """Processes a variable number of positional and keyword arguments."""
    print("Positional arguments (*args):")
    for arg in args:
        print(f"- {arg}")

    print("\nKeyword arguments (**kwargs):")
    for key, value in kwargs.items():
        print(f"- {key}: {value}")

process_items(1, 2, 3, name="Bob", age=30)

4.3 Python Lambda Functions

Lambda functions, also known as anonymous functions, are small, single-expression functions that do not require a formal definition using the def keyword. They are defined using the lambda keyword.

Syntax:

lambda arguments: expression
  • lambda: Keyword to declare a lambda function.
  • arguments: One or more arguments, separated by commas.
  • expression: A single expression that is evaluated and returned.

Lambda functions are often used where a small function is needed for a short period, such as in conjunction with higher-order functions like map(), filter(), and sorted().

Example 1: A simple lambda function.

# A lambda function that adds 10 to a number
add_ten = lambda x: x + 10
print(add_ten(5))  # Output: 15

Example 2: Lambda function with multiple arguments.

# A lambda function that multiplies two numbers
multiply = lambda x, y: x * y
print(multiply(4, 6))  # Output: 24

Example 3: Using lambda with filter().

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Filter out even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Example 4: Using lambda with map().

The map() function applies a given function to each item of an iterable and returns an iterator of the results.

numbers = [1, 2, 3, 4, 5]

# Square each number in the list
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Example 5: Using lambda with sorted().

The sorted() function sorts an iterable. A lambda function can be used to define a custom sorting key.

# Sorting a list of tuples based on the second element of each tuple
data = [(1, 'B'), (3, 'A'), (2, 'C')]
sorted_data = sorted(data, key=lambda item: item[1])
print(sorted_data)  # Output: [(3, 'A'), (1, 'B'), (2, 'C')]

Key Characteristics of Lambda Functions:

  • They are anonymous (no explicit def name).
  • They can take any number of arguments but can only have one expression.
  • The expression is evaluated and returned.
  • They are syntactically restricted to a single expression.

Lambda functions are powerful for concise, on-the-fly function creation, especially when working with functional programming concepts in Python.

Python Functions: Built-in, User-Defined & Lambda