Skip to content
Cover image for: Python Functions: Complete Practical Guide
#pythonBeginner

Python Functions: Complete Practical Guide

May 1, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-functions-complete-practical-guide

Learn Python functions from basics to advanced with practical examples. Covers function definition, parameters vs arguments, return values, default and keyword arguments, *args for variable positional arguments, **kwargs for variable keyword arguments, LEGB scope resolution rules, lambda functions for inline operations, closures that capture enclosing state, decorators for modifying function behavior, and recursion with proper base case handling and stack management.

Quick Summary

A lambda function is a small anonymous function.

Let's create a function (with docstring)

Python function to determine if a number is even or odd using modulo operator

Explanation

  • The function takes an integer input parameter and uses the modulo operator (%) to check if the number is divisible by 2
  • When the remainder of division by 2 equals zero, the number is classified as even
  • If the remainder is non-zero, the number is classified as odd
  • The function returns a string value indicating whether the input number is 'even' or 'odd'
  • This implementation provides a simple mathematical approach to parity checking for integer values
python

Function-based even number detection and iteration through numeric range

Explanation

  • The code iterates through numbers from 1 to 10 using a for loop with range(1,11)
  • Each number in the range is passed as input to an is_even() function that presumably checks if the number is divisible by 2
  • The function's return value (True or False) is printed for each iteration
  • This demonstrates a basic pattern for testing mathematical properties across a sequence of integers
  • The code structure shows how to combine looping constructs with function calls for repetitive validation tasks
python

Output

text

Retrieve the documentation string for the is_even function in Python

Explanation

  • The code accesses the __doc__ attribute of the is_even function, which contains its documentation string.
  • This attribute is useful for understanding the purpose and usage of the function without needing to read the source code.
  • If is_even is defined with a docstring, this will return that string; otherwise, it will return None.
  • This practice is common in Python to enhance code readability and provide guidance to users of the function.
python

Output

text

Retrieve and display the documentation string of the is_even function in Python.

Explanation

  • The code uses the built-in print function to output information to the console.
  • is_even.__doc__ accesses the documentation string (docstring) of the is_even function, which describes its purpose and usage.
  • This is useful for understanding how to use the function without needing to look at the source code.
  • If is_even is not defined, this will raise a NameError.
  • The output will be None if the function does not have a docstring.
python

Output

text

2 Point of views

Function to Determine if a Given Integer is Even or Odd

Explanation

  • Defines a function is_even that takes a single integer input.
  • Checks if the input is of type integer before proceeding with the logic.
  • Uses the modulus operator to determine if the number is even or odd, returning 'even' or 'odd' accordingly.
  • Returns an error message if the input is not a valid integer.
  • Includes a docstring that describes the function's purpose, input, output, and creation date.
python

Parameters vs Arguments

Types of Arguments:

  • Default Argument
  • Positional Argument
  • Keyword Argument

This function calculates the power of a number raised to an exponent.

Explanation

  • The function power takes two parameters, a (the base) and b (the exponent).
  • It uses the exponentiation operator ** to compute a raised to the power of b.
  • The result is returned as the output of the function.
  • This function can handle both integer and floating-point numbers for a and b.
  • It can be used in mathematical calculations where exponentiation is required.
python

This code snippet demonstrates how to calculate the power of a number using a function.

Explanation

  • The function power is called with an argument of 2, indicating that the base number is 2.
  • The code likely computes 2 raised to a certain exponent, although the exponent is not specified in the snippet.
  • The result of the power calculation would typically be returned or printed, depending on the implementation of the power function.
  • This snippet is useful for understanding how to utilize functions for mathematical operations in Python.
python

Output

text

This Python function demonstrates the use of default arguments for exponentiation.

Explanation

  • The function power takes two parameters, a and b, both of which have default values of 1.
  • If no arguments are provided when calling the function, it will return 1**1, which equals 1.
  • The function calculates a raised to the power of b using the exponentiation operator **.
  • Users can override the default values by passing different arguments when calling the function, allowing for flexible usage.
  • This design simplifies function calls for common cases while still allowing for customization.
python

This code snippet calls a function named power to execute its defined behavior.

Explanation

  • The power() function is invoked, which suggests it performs a specific operation related to exponentiation or power calculations.
  • Without additional context or parameters, the function's internal logic and output are not visible in this snippet.
  • It is essential to ensure that the power function is defined elsewhere in the code for this call to be valid.
  • The absence of arguments indicates that the function may use default values or global variables.
python

Output

text

Understanding the Use of Positional Arguments in a Python Function Call

Explanation

  • The function power is called with two positional arguments: 2 and 3.
  • The first argument 2 is assigned to the first parameter of the function, while the second argument 3 is assigned to the second parameter.
  • Positional arguments are matched to function parameters based on their order in the function call.
  • This means that the function will interpret 2 as the base and 3 as the exponent if power is defined accordingly.
  • If the function power is not defined to accept two parameters, an error will occur.
python

Output

text

Demonstrating the use of keyword arguments in a function call in Python

Explanation

  • The function power is called with keyword arguments, where b is set to 3 and a is set to 2.
  • Keyword arguments allow the caller to specify values for parameters by name, improving code readability.
  • The order of the arguments does not matter when using keyword arguments, as they are explicitly defined.
  • This approach is particularly useful when a function has multiple parameters, making it clear which value corresponds to which parameter.
  • Ensure that the function power is defined to accept parameters a and b for this call to work correctly.
python

Output

text

*args and **kwargs

*args and **kwargs are special Python keywords that are used to pass the variable length of arguments to a function

This function demonstrates how to multiply two numbers using Python's standard function parameters.

Explanation

  • The function multiply takes two parameters, a and b, which represent the numbers to be multiplied.
  • It returns the product of a and b using the multiplication operator *.
  • This code snippet illustrates a basic usage of function parameters in Python without utilizing variable-length arguments.
  • The function can be called with any two numeric values to obtain their product.
python

This code snippet demonstrates how to multiply two numbers using a function call in Python.

Explanation

  • The function multiply is called with two arguments, 2 and 3.
  • It performs multiplication of the two numbers provided as inputs.
  • The result of the multiplication is typically returned or printed, although the return statement is not shown in this snippet.
  • This operation showcases basic arithmetic functionality in Python.
python

Output

text

This function multiplies three input numbers and returns the result.

Explanation

  • The function multiply takes three parameters: a, b, and c.
  • It calculates the product of these three parameters using the multiplication operator *.
  • The result of the multiplication is returned to the caller.
  • This function can be used to quickly compute the product of any three numerical values.
python

This code snippet demonstrates how to call a function to multiply multiple numbers together.

Explanation

  • The function multiply is invoked with three arguments: 2, 3, and 4.
  • It is expected that the multiply function will return the product of these numbers.
  • The result of the multiplication will depend on the implementation of the multiply function, which is not shown here.
  • This snippet illustrates the concept of passing multiple parameters to a function in Python.
python

Output

text

This function multiplies an arbitrary number of arguments and returns the product.

Explanation

  • The function multiply accepts a variable number of arguments using *args, allowing for flexibility in input.
  • It initializes a variable product to 1, which will hold the cumulative product of the input values.
  • A for loop iterates through each argument in args, multiplying each value with product.
  • The function prints the args tuple to show the input values received.
  • Finally, it returns the computed product of all the input arguments.
python

Demonstrating the usage of a multiply function with varying arguments in Python

Explanation

  • The code calls a function named multiply with different sets of arguments.
  • The first call, multiply(1,2), passes two integers to the function.
  • The second call, multiply(2,3,4,5,6), passes five integers, showcasing the function's ability to handle multiple arguments.
  • The output of each call is printed, indicating the results of the multiplication operations performed by the multiply function.
  • This snippet highlights the flexibility of Python functions in accepting variable numbers of arguments.
python

Output

text

This function calculates the product of an arbitrary number of input values.

Explanation

  • The function multiply accepts a variable number of arguments using the *madhu syntax, allowing for flexibility in input.
  • It initializes a variable product to 1, which will hold the cumulative product of the input values.
  • A for loop iterates through each value in madhu, multiplying them together and updating the product variable.
  • The function prints the original input values and returns the final product after the loop completes.
python

This code snippet demonstrates how to print the result of multiplying multiple numbers using a function.

Explanation

  • The print function is used to output the result of the multiply function.
  • The multiply function takes a variable number of arguments (in this case, the numbers 1 through 9).
  • The code assumes that the multiply function is defined elsewhere in the program, which performs the multiplication of all provided arguments.
  • The output will be the product of all the numbers passed to the multiply function.
python

Output

text

Dynamically handle multiple keyword arguments in a Python function

Explanation

  • The function display accepts any number of keyword arguments using **kwargs, which collects them into a dictionary.
  • Inside the function, a loop iterates over the key-value pairs in kwargs using the items() method.
  • Each key and its corresponding value are printed in the format "key -> value".
  • This approach allows for flexible function calls with varying numbers of named parameters.
  • It is particularly useful for functions that require optional parameters or when the exact number of arguments is not known in advance.
python

Python function call displaying capital cities of South Asian countries

Explanation

  • This code calls a display function with three keyword arguments representing country-capital pairs
  • The function parameters include india=delhi, srilanka=colombo, and nepal=kathmandu
  • This demonstrates passing multiple named parameters to a function in Python
  • The syntax uses keyword arguments which makes the code more readable and self-documenting
  • This approach allows functions to accept variable numbers of named parameters using **kwargs pattern
python

Output

text

Python function demonstrating variable keyword arguments and dictionary iteration

Explanation

  • The function accepts arbitrary keyword arguments using the **madhu parameter, which collects all keyword arguments into a dictionary
  • It iterates through the dictionary items using the .items() method to access both keys and values
  • Each key-value pair is printed in a formatted string showing the key followed by '->' and then the corresponding value
  • This pattern enables flexible functions that can handle varying numbers of named parameters
  • The function demonstrates Python's unpacking operator and dictionary iteration capabilities
python

Python function call displaying capital cities of South Asian countries

Explanation

  • This code calls a display function with three keyword arguments representing country-capital pairs
  • The function parameters include india=delhi, srilanka=colombo, and nepal=kathmandu
  • This demonstrates passing multiple named parameters to a function in Python
  • The syntax uses keyword arguments which makes the code more readable and self-documenting
  • This approach allows functions to accept variable numbers of named parameters using **kwargs pattern
python

Output

text
Points to remember while using *args and **kwargs
  • order of the arguments matter(normal -> *args -> **kwargs)
  • The words “args” and “kwargs” are only a convention, you can use any name of your choice

Without return statement

This code appends an element to a list and prints the result of the operation.

Explanation

  • The list L is initialized with three integer elements: 1, 2, and 3.
  • The append method is called on the list L to add the integer 4 to the end of the list.
  • The print function outputs the result of the append method, which is None, since append modifies the list in place and does not return a value.
  • After execution, the list L will contain four elements: [1, 2, 3, 4].
python

Output

text

This code snippet demonstrates how to add an element to a list in Python.

Explanation

  • A list L is initialized with three integer elements: 1, 2, and 3.
  • The append() method is called on the list L to add the integer 4 as the last element.
  • The print() function outputs the updated list, which now contains four elements: [1, 2, 3, 4].
python

Output

text

Variable Scope

Understanding the interaction between global and local variables in Python functions

Explanation

  • The function g(y) attempts to print the value of x, which is defined as a global variable outside the function.
  • Inside the function, x is accessed directly, demonstrating that global variables can be used within local scopes.
  • The function prints x and x + 1, which will output 5 and 6 respectively when called with g(x).
  • After calling the function, the global variable x is printed again, confirming its value remains unchanged at 5.
  • This code snippet illustrates the concept of variable scope in Python, highlighting how global variables can be accessed within functions.
python

Output

text

Understanding variable scope and reference in Python functions

Explanation

  • The function f(y) attempts to increment a variable x that is not defined within its local scope, leading to an UnboundLocalError.
  • The variable x is defined globally with an initial value of 5 before the function is called.
  • When f(x) is invoked, it passes the value of x (5) to the parameter y, but x inside the function is treated as a local variable due to the increment operation.
  • The print(x) statement outside the function will correctly output the global value of x, which remains 5, since the function does not modify it.
  • To fix the error, x should be declared as global inside the function if the intention is to modify the global variable.
python

Output

text

This Python function demonstrates variable scope and modification within a function.

Explanation

  • The function f(y) initializes a local variable x to 1 and increments it by 1, resulting in x being 2.
  • The print(x) statement inside the function outputs the local value of x, which is 2.
  • The variable x outside the function is set to 5, but it remains unchanged since the function modifies a local variable.
  • The final print(x) statement outputs the global value of x, which is still 5, demonstrating the concept of variable scope in Python.
python

Output

text

This code demonstrates function scope and variable manipulation in Python.

Explanation

  • The function f(x) takes an argument x, increments it by 1, and prints the new value.
  • The original variable x in the main program remains unchanged due to Python's handling of variable scope.
  • The function returns the incremented value, which is stored in the variable z.
  • The final print statements display the values of z and the original x, illustrating the difference between local and global variable states.
python

Output

text

Nested Functions

This Python code demonstrates nested function definitions and their execution.

Explanation

  • The outer function f is defined, which contains another function g inside it.
  • The inner function g prints a message when called, indicating its execution.
  • The outer function f also prints a message when executed, showing its own execution context.
  • However, the inner function g is not called within f, so it will not execute unless explicitly invoked.
  • This structure illustrates the concept of function scope and encapsulation in Python.
python

This code snippet demonstrates the invocation of a function in Python.

Explanation

  • The code calls a function named f(), which is expected to be defined elsewhere in the code.
  • The parentheses () indicate that the function is being executed.
  • If f() requires any arguments, they would need to be provided within the parentheses.
  • The function's behavior and output depend on its internal implementation, which is not shown in this snippet.
  • This is a fundamental aspect of Python programming, showcasing how functions are utilized to encapsulate reusable code.
python

Output

text

This code defines nested functions and demonstrates their invocation in Python.

Explanation

  • The outer function f contains an inner function g.
  • When f is called, it executes the inner function g first.
  • The inner function g prints the message 'inside function g' to the console.
  • After g is executed, control returns to f, which then prints 'inside function f'.
  • This showcases the concept of function nesting and scope in Python.
python

This code snippet demonstrates the invocation of a function in Python.

Explanation

  • The code calls a function named f(), which is expected to be defined elsewhere in the code.
  • The parentheses () indicate that the function is being executed.
  • If f() requires any arguments, they would need to be provided within the parentheses.
  • The function's behavior and output depend on its internal implementation, which is not shown in this snippet.
  • This is a fundamental aspect of Python programming, showcasing how functions are utilized to encapsulate reusable code.
python

Output

text

Understanding variable scope and function nesting in Python through a simple function example

Explanation

  • The function g(x) takes an integer parameter x and defines a nested function h() within it.
  • Inside h(), the local variable x is reassigned to the string 'abc', but this does not affect the x in g(x) due to Python's scoping rules.
  • The original x is incremented by 1 before being printed, resulting in the output 'in g(x): x = 4'.
  • The nested function h() is called, but its changes to x are local and do not impact the outer function's x.
  • Finally, the function g(x) returns the modified value of x, which is 4, and this value is assigned to z.
python

Output

text

Understanding nested function behavior and variable scope in Python

Explanation

  • The function g(x) takes an integer x, increments it by 1, and prints the updated value.
  • Inside g(x), a nested function h(x) is defined, which also increments its parameter x by 1 and prints the result.
  • When g(x) is called with x = 3, it increments x to 4, prints it, and then calls h(x) with the new value.
  • The nested function h(x) increments its own x to 5 and prints this value, demonstrating how nested functions can have their own scope.
  • The main program prints the original x (which remains 3) and the return value z from g(x) (which is 4), illustrating the difference between local and global variable scopes.
python

Output

text

Functions are 1st class citizens

Understanding the type and memory address of a function in Python

Explanation

  • The square function takes a single argument num and returns its square by raising it to the power of 2.
  • The type(square) function call returns the type of the square function, which is <class 'function'>.
  • The id(square) function call returns the memory address of the square function, which is a unique identifier for the function object in memory.
  • This code snippet demonstrates how to inspect the properties of a function in Python, specifically its type and memory location.
python

Output

text

This code snippet demonstrates variable reassignment and function referencing in Python.

Explanation

  • The variable x is reassigned to reference the function square, which is assumed to be defined elsewhere in the code.
  • The print(x) statement outputs the function object that x now references.
  • The print(id(x)) statement displays the memory address of the function object, confirming that x points to the same object as square.
  • The print(x(3)) statement calls the function square with an argument of 3, outputting the result of the function execution.
python

Output

text

This code snippet demonstrates how to delete a function from the current namespace in Python.

Explanation

  • The del statement is used to remove the specified object from the current scope.
  • In this case, the function square is being deleted, which means it can no longer be called or referenced.
  • This operation can help manage memory and avoid name clashes in larger codebases.
  • After executing this line, any attempt to call square will result in a NameError.
python

This code snippet demonstrates how to call a function to calculate the square of a number.

Explanation

  • The function square is invoked with the argument 3.
  • It is expected that the square function computes the value of 3 multiplied by itself.
  • The output will be 9, representing the square of the input number.
  • Ensure that the square function is defined elsewhere in the code for this call to work correctly.
python

Output

text

This code snippet demonstrates a function call with an argument in Python.

Explanation

  • The code calls a function named x and passes the integer 3 as an argument.
  • The function x must be defined elsewhere in the code for this call to execute successfully.
  • The behavior of the function will depend on its implementation, which is not provided in this snippet.
  • If x is not defined, this will raise a NameError indicating that x is not recognized.
python

Output

text

This code snippet assigns the value of variable x to the variable square.

Explanation

  • The variable square is created to store a value.
  • The value assigned to square is taken from another variable x.
  • This operation does not perform any calculations; it simply copies the value of x.
  • The variable x must be defined prior to this line for the assignment to be valid.
python

This code snippet demonstrates how to store and invoke a function within a list in Python.

Explanation

  • A list L is created containing integers and a function reference named square.
  • The list is printed, displaying its contents, which include both numbers and the function.
  • The last element of the list, which is the square function, is called with the argument 3 using negative indexing.
  • The result of the function call is printed, showing the output of squaring the number 3.
  • This illustrates the flexibility of Python lists to hold different types of elements, including functions.
python

Output

text

Understanding the behavior of sets with immutable data types in Python

Explanation

  • The code attempts to create a set s containing a square, but the variable square is not defined in the snippet.
  • Sets in Python are collections that do not allow duplicate elements and are mutable, meaning you can add or remove items.
  • The comment indicates that functions or immutable data types cannot be added to a set, as sets only accept hashable types.
  • If square were defined as a hashable type (like an integer), the set would successfully contain that value.
  • The final line s is likely intended to display the contents of the set, but without a defined square, it will raise an error.
python

Output

text

This code demonstrates the creation and invocation of a nested function in Python that returns another function.

Explanation

  • The function f() defines a nested function x(a, b) that takes two parameters and returns their sum.
  • When f() is called, it returns the nested function x, which can then be invoked with two arguments.
  • The expression f()(3, 4) calls f() to get x, and immediately calls x with the arguments 3 and 4, resulting in 7.
  • The second (3, 4) in f()(3, 4)(3, 4) is incorrect as x is not designed to be called again; it should raise an error or return a value based on the first call.
  • The final print(val) outputs the result of the first function call, which is 7.
python

Output

text

Python nested function closure returning inner function with parameter binding

Explanation

  • The code defines a nested function structure where f() returns the inner function x, which itself returns another inner function y
  • Function y performs multiplication of two parameters and serves as the final callable in the chain
  • When f() is invoked, it returns x, then x(3,4) returns y, and finally y(3,4) executes the multiplication operation
  • The outer functions act as closures that encapsulate the inner function y while maintaining access to their local scope
  • This demonstrates Python's function closure mechanism where nested functions can capture and remember variables from their enclosing scopes
python

Output

text

Demonstrating function passing and execution in Python through higher-order functions

Explanation

  • The code defines two functions where func_a prints a message and func_b takes another function as parameter
  • func_b executes the passed function by calling it with parentheses and returns its result
  • When func_b is called with func_a as argument, it first prints 'inside func_c', then executes func_a which prints 'inside func_a'
  • The return value of func_b is the return value of func_a, which is None since func_a has no explicit return statement
  • This demonstrates how functions can be treated as first-class objects and passed as arguments to other functions in Python
python

Output

text

Benefits of using a Function

  • Code Modularity
  • Code Readibility
  • Code Reusability

Lambda Function A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

This code defines a lambda function to compute the square of a number.

Explanation

  • A lambda function a is created that takes one argument x and returns x squared (x**2).
  • The print statement calls the lambda function with the argument 4, which computes 4^2.
  • The output of the code will be 16, as it prints the result of squaring the input value.
  • This concise syntax allows for quick function definitions without formally defining a standard function using def.
python

Output

text

This code defines a lambda function to sum two numbers and prints the result.

Explanation

  • A lambda function named a is created, which takes two parameters x and y.
  • The function returns the sum of x and y when called.
  • The print statement invokes the lambda function with arguments 2 and 3.
  • The output of the function, which is 5, is displayed on the console.
python

Output

text

Diff between lambda vs Normal Function

  • No name
  • lambda has no return value(infact,returns a function)
  • lambda is written in 1 line
  • not reusable

Then why use lambda functions? They are used with HOF (Higher Order Functions)

This code defines a lambda function to check for the presence of the letter 'a' in a string.

Explanation

  • A lambda function named a is created, which takes one argument x.
  • The function checks if the character 'a' is present in the input string x.
  • The print statement calls the lambda function with the argument 'Madhu', which returns False since 'a' is not in 'Madhu'.
  • This code demonstrates the use of lambda functions for simple conditional checks in Python.
python

Output

text

This code defines a lambda function to determine if a number is even or odd.

Explanation

  • A lambda function a is created that takes one argument x.
  • It uses a conditional expression to return 'even' if x is divisible by 2, otherwise it returns 'odd'.
  • The function is then called with the argument 6, which results in the output 'even'.
  • This snippet demonstrates a concise way to define simple functions in Python using lambda expressions.
python

Output

text

Higher Order Functions

  • If a function returns another function
  • A function uses another function as input

This code defines a function to square numbers and applies it to a list using a transformation function.

Explanation

  • The square function takes an input x and returns its square by raising it to the power of 2.
  • The transform function accepts a function f and a list L, iterating over each element in L.
  • For each element in L, it applies the function f and appends the result to the output list.
  • Finally, the output list is printed, showing the transformed values.
  • The list L contains integers from 1 to 5, and the transform function is called with square to compute their squares.
python

Output

text

This code applies a cubic transformation to each element in a list using a lambda function.

Explanation

  • The transform function takes two arguments: a function (in this case, a lambda function) and a list L.
  • The lambda function lambda x: x**3 defines the operation to be performed, which is cubing each element.
  • The code applies this transformation to every element in the list L, resulting in a new list where each element is raised to the power of three.
  • This is a concise way to perform operations on collections in Python, leveraging functional programming concepts.
python

Output

text

Map

Squaring each element in a list using a lambda function and map in Python

Explanation

  • Utilizes the map() function to apply a transformation to each item in the provided list.
  • The transformation is defined by a lambda function that squares each element (x**2).
  • The input list consists of integers from 1 to 5.
  • The result is a map object containing the squared values, which can be converted to a list for easier viewing.
  • This approach is efficient for applying operations to all elements in an iterable without the need for explicit loops.
python

Output

text

This code snippet demonstrates how to apply a function to each element in a list using map and lambda in Python.

Explanation

  • The map function applies a specified function to each item of the iterable (in this case, a list of numbers).
  • A lambda function is defined to square each element (x**2).
  • The input list [1, 2, 3, 4, 5] is passed to map, which processes each number through the lambda function.
  • The result is a map object containing the squared values, which can be converted to a list if needed.
  • This approach is concise and leverages functional programming concepts in Python.
python

Output

text

This code snippet labels each item in a list as 'even' or 'odd' based on its value.

Explanation

  • A list L is defined containing integers from 1 to 5.
  • The map function applies a lambda function to each element of the list L.
  • The lambda function checks if an element is even or odd using the modulus operator %.
  • If the element is even (x % 2 == 0), it returns the string 'even'; otherwise, it returns 'odd'.
  • The result is a map object containing the labels for each item, which can be converted to a list if needed.
python

Output

text

Extracting gender information from a list of user dictionaries in Python

Explanation

  • The code defines a list of dictionaries, each representing a user with attributes such as name, age, and gender.
  • It utilizes the map function to apply a lambda function to each user dictionary in the list.
  • The lambda function retrieves the 'gender' value from each user dictionary.
  • The result is an iterable containing the gender of each user, which can be converted to a list if needed.
  • This approach efficiently processes the list without the need for explicit loops.
python

Output

text

Filter

Filtering a list to retrieve numbers greater than five using a lambda function

Explanation

  • The code defines a list L containing integers from 3 to 7.
  • It utilizes the filter function to apply a condition defined by a lambda function.
  • The lambda function checks if each element x in the list is greater than 5.
  • The result is a filter object that contains only the numbers from the list that meet the condition.
  • To convert the filter object to a list, you can wrap it with list(), which is implied in the snippet.
python

Output

text

This code filters a list to identify elements greater than five using a lambda function.

Explanation

  • Utilizes the map function to apply a lambda expression to each element in the list L.
  • The lambda function checks if each element x is greater than 5, returning True or False.
  • The result is an iterable of boolean values indicating whether each element meets the condition.
  • To convert the result into a list, the list() function can be used, though it's not shown in the snippet.
  • This approach is efficient for applying a condition across all elements in a list without explicit loops.
python

Output

text

Filtering a list to find fruits that contain the letter 'a'

Explanation

  • The code defines a list of fruits named fruits containing three items: 'apple', 'guava', and 'cherry'.
  • It uses the filter function combined with a lambda function to iterate through each fruit in the list.
  • The lambda function checks if the letter 'a' is present in each fruit's name.
  • The result is a filtered list of fruits that contain the letter 'a', which will include 'apple' and 'guava'.
python

Output

text

This code checks if the letter 'a' is present in each fruit name from a list.

Explanation

  • Utilizes the map function to apply a transformation to each element in the fruits list.
  • The lambda function takes each fruit name x and returns True if 'a' is found in the name, otherwise returns False.
  • The result is a map object containing boolean values indicating the presence of 'a' in each fruit name.
  • This approach is efficient for processing lists without the need for explicit loops.
  • To convert the map object to a list, you can wrap it with list().
python

Output

text

Reduce

Calculate the sum of a list of numbers using Python's functools module

Explanation

  • The code imports the functools module, which provides higher-order functions for functional programming.
  • It uses functools.reduce() to apply a lambda function that sums two numbers across a list of integers.
  • The lambda function takes two arguments, x and y, and returns their sum.
  • The list [1, 2, 3, 4, 5] is passed as the iterable to reduce(), which processes the elements cumulatively.
  • The final output is the total sum of the numbers in the list, which is 15.
python

Output

text

Filtering a list to retain only values greater than two using a lambda function

Explanation

  • Utilizes the filter function to apply a condition to each element in the list.
  • The lambda function defines the condition, checking if each element x is greater than 2.
  • The input list consists of integers from 1 to 5.
  • The result is an iterable containing only the elements that satisfy the condition, which can be converted to a list if needed.
  • This approach is concise and leverages functional programming concepts in Python.
python

Output

text

This code filters a list to identify elements greater than two using a lambda function.

Explanation

  • The map function applies a given function to all items in the input list.
  • A lambda function is defined to check if each element x is greater than 2.
  • The input list consists of integers from 1 to 5.
  • The result is an iterable of boolean values indicating whether each element meets the condition.
  • To convert the output to a list, you can wrap the map function with list().
python

Output

text

This code snippet finds the minimum value in a list using a functional programming approach.

Explanation

  • Utilizes functools.reduce to apply a function cumulatively to the items of the list.
  • The lambda function compares two values, returning the smaller one.
  • The list [11, 21, 31, 4, 51] is the input from which the minimum value is derived.
  • The result of the reduction is the smallest number in the list, which is 4.
  • This approach is a concise way to perform operations on iterables without explicit loops.
python

Output

text

Problem-1: Write a Python function that takes a list and returns a new list with unique elements of the first list.

Exercise 1:

Input:

bash

Output:

bash

This function filters a list to return only unique elements.

Explanation

  • The function return_unique initializes an empty list res to store unique items.
  • It iterates through each element i in the input list L.
  • For each element, it checks if i is not already in res before appending it, ensuring uniqueness.
  • Finally, the function returns the list res, which contains only the unique elements from L.
  • In the provided example, calling return_unique(L) with the list [1,2,3,3,3,3,4,5] results in [1, 2, 3, 4, 5].
python

Output

text

Problem-2: Write a Python function that accepts a hyphen-separated sequence of words as parameter and returns the words in a hyphen-separated sequence after sorting them alphabetically.

Example 1:

Input:

bash

Output:

bash

This code sorts a hyphen-separated string of colors in alphabetical order.

Explanation

  • The function sort_sequence takes a string seq as input, which contains colors separated by hyphens.
  • It splits the string into a list of colors using the split('-') method.
  • The list of colors is then sorted alphabetically using the sorted() function.
  • Each sorted color is appended to a temporary list temp.
  • Finally, the sorted colors are joined back into a single string with hyphens and returned.
python

Output

text

Problem 3: Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.

text

Counting lowercase and uppercase characters in a string using Python function

Explanation

  • The function lower_upper takes a string input and initializes counters for lowercase and uppercase characters
  • It iterates through each character in the string and uses islower() and isupper() methods to categorize characters
  • The function returns a tuple containing the count of lowercase and uppercase characters respectively
  • The code demonstrates string character analysis by processing a sample string with mixed case letters
  • Output shows the total count of lowercase characters (19) and uppercase characters (7) in the given string
python

Output

text

Problem 4: Write a Python program to print the even numbers from a given list.

text

Function that filters even numbers from a list using modular arithmetic

Explanation

  • The function is_even takes a list of integers as input and returns a new list containing only the even numbers
  • It iterates through each element in the input list using a for loop
  • For each number, it checks if the remainder when divided by 2 equals zero using the modulo operator (%)
  • Numbers that pass the even number test are appended to a result list which is returned at the end
  • The function call with [1,2,3,4,5,6,7] demonstrates filtering out odd numbers to return only [2,4,6]
python

Output

text

Problem 5: Write a Python function to check whether a number is perfect or not.

A Perfect number is a number that is half the sum of all of its positive divisors (including itself).

Example :

text

This function checks if a number is a perfect number by summing its divisors.

Explanation

  • The function perfect_num takes an integer num as input and initializes a variable sum to zero.
  • It iterates through all integers from 1 to num - 1, checking if each integer is a divisor of num.
  • If a divisor is found, it adds that divisor to the sum.
  • Finally, the function returns True if the sum of the divisors equals num, indicating that num is a perfect number; otherwise, it returns False.
  • The call perfect_num(29) checks if 29 is a perfect number, which it is not, so the function will return False.
python

Output

text

Problem-6: Write a Python function to concatenate any no of dictionaries to create a new one.

text

Merging multiple dictionaries into a single dictionary in Python

Explanation

  • The function merge_dict accepts a variable number of dictionary arguments using *kwargs.
  • It initializes an empty dictionary d to store the merged results.
  • The function iterates over each dictionary passed in kwargs and updates d with the contents of each dictionary using the update() method.
  • Finally, it returns the merged dictionary containing all key-value pairs from the input dictionaries.
  • The provided dictionaries dic1, dic2, and dic3 are merged by calling merge_dict, resulting in a single dictionary with all entries combined.
python

Output

text

Problem-7 Write a python function that accepts a string as input and returns the word with most occurence.

text
text

Identify and print the most frequently used word in a given string

Explanation

  • The function most_used takes a string s as input and splits it into individual words.
  • It uses a dictionary d to count the occurrences of each word in the string.
  • After populating the dictionary, it finds the maximum count of occurrences using max(d.values()).
  • The function then iterates through the dictionary to find and print the first word that matches the maximum count along with its frequency.
python

Output

text

Problem-8 Write a python function that receives a list of integers and prints out a histogram of bin size 10

text
text

Create a histogram from a list of numbers by binning them into ranges

Explanation

  • The function histogram takes a list of numbers L as input and calculates the minimum and maximum bins based on the values in L.
  • It initializes a dictionary d to store the counts of numbers falling within specified ranges (bins) of 10 units each.
  • A nested loop iterates through each bin range, counting how many numbers from the list fall within that range.
  • The counts are stored in the dictionary with keys formatted as "start-end" (e.g., "11-20").
  • Finally, the function returns the dictionary containing the histogram data for the provided list.
python

Output

text

Problem-9 Write a python function that accepts a list of 2D co-ordinates and a query point, and then finds the the co-ordinate which is closest in terms of distance from the query point.

text
text

Calculate the nearest point from a list based on Euclidean distance in Python

Explanation

  • Defines a function shortest_dist that takes a list of points and a query point as input.
  • Computes the Euclidean distance from each point in the list to the query point using the distance formula.
  • Stores the calculated distances in a temporary list temp.
  • Identifies the index of the minimum distance using sorted and retrieves the corresponding point from the original list.
  • Returns the point that is closest to the query point.
python

Output

text

Problem-10:Write a python program that receives a list of strings and performs bag of word operation on those strings

https://en.wikipedia.org/wiki/Bag-of-words_model

This code implements a Bag of Words model to analyze word frequency in a list of sentences.

Explanation

  • The function bow takes a list of strings L as input, representing sentences.
  • It initializes a set vocab to store unique words found in the sentences.
  • The first loop populates vocab by splitting each sentence into words and updating the set.
  • The second loop constructs a frequency list result, where each sublist corresponds to a sentence and contains counts of each word in vocab.
  • Finally, the function prints the vocabulary and returns the frequency list.
python

Output

text

###Problem 11: Write a Python program to add three given lists using Python map and lambda.

This code snippet demonstrates how to sum corresponding elements from multiple lists using a lambda function.

Explanation

  • The code defines three lists, L1, L2, and L3, each containing three integers.
  • It uses the map function to apply a lambda function that takes three arguments (x, y, z) and returns their sum.
  • The map function iterates over the three lists in parallel, summing the elements at the same index.
  • The result is a new list containing the sums of the corresponding elements from L1, L2, and L3, which would be [12, 15, 18].
  • This approach is efficient for combining multiple lists element-wise without the need for explicit loops.
python

Output

text

###Problem-12:Write a Python program to create a list containing the power of said number in bases raised to the corresponding number in the index using Python map. Input:

text

Output:

text

This code snippet demonstrates how to apply a power operation to elements of a list using a lambda function and the map function.

Explanation

  • A list list1 is defined containing integers from 1 to 6.
  • The map function is used to apply a lambda function to each element of list1 and its corresponding index from range(len(list1)).
  • The lambda function takes two arguments, x (the element from list1) and y (the index), and computes x**y, which raises x to the power of y.
  • The result is a map object that contains the results of the power operations for each element in list1.
  • To convert the map object to a list, it can be wrapped with list(), but this is not shown in the snippet.
python

Output

text

###Problem-13 Using filter() and list() functions and .lower() method filter all the vowels in a given string.

This code filters vowels from a given string using a lambda function.

Explanation

  • The code initializes a string str1 containing a sentence about the FIFA World Cup.
  • It uses the filter function to iterate over each character in str1.
  • A lambda function checks if each character (converted to lowercase) is a vowel by comparing it to the string 'aeiou'.
  • The filter function returns an iterable containing only the characters that are vowels from the original string.
  • The result is a collection of vowels found in the input string.
python

Output

text

Problem-14: Use reduce to convert a 2D list to 1D

This code snippet demonstrates how to flatten a list of lists using Python's functools.reduce function.

Explanation

  • The variable ini_list is a list containing three sublists, each with integer elements.
  • The functools.reduce function is imported to apply a rolling computation to the items of ini_list.
  • A lambda function is used within reduce to sum two lists together, effectively concatenating them.
  • The result is a single flattened list containing all the integers from the original nested lists.
  • This approach is useful for combining multiple lists into one without using explicit loops.
python

Output

text

Problem 15- A dictionary contains following information about 5 employees:

  • First name
  • Last name
  • Age
  • Grade(Skilled,Semi-skilled,Highly skilled) Write a program using map/filter/reduce to a list of employees(first name + last name) who are highly skilled

This code initializes a list of employee dictionaries with personal details and skill levels.

Explanation

  • A list named employees is created to store multiple employee records.
  • Each employee is represented as a dictionary containing their first name (fname), last name (lname), age, and skill grade (grade).
  • The skill grades include categories such as 'skilled', 'semi-skilled', and 'highly-skilled', indicating the employee's proficiency level.
  • This structure allows for easy access and manipulation of employee data for further processing or analysis.
python

Extracting full names of highly-skilled employees from a list of dictionaries

Explanation

  • Utilizes filter to create a subset of the employees list, retaining only those with a grade of 'highly-skilled'.
  • Applies map to transform the filtered list by concatenating the fname and lname fields of each employee into a full name string.
  • The lambda functions are used for both filtering and mapping, providing concise inline definitions for the operations.
  • The final output is a list of full names of employees who meet the specified criteria.
python

Output

text

Next in this series: Recursion in Python: From Basics to Advanced Problem Solving →

Frequently Asked Questions

The function uses the modulo operator % to check if the number is divisible by 2. If the remainder is zero, the number is even; otherwise, it is odd.
The iseven function returns a string value indicating whether the input number is 'even' or 'odd'.
You can access the documentation string by using the iseven.__doc__ attribute, which contains the function's docstring.
If the iseven function does not have a docstring, accessing iseven.__doc__ will return None.
The for loop iterates through numbers from 1 to 10, passing each number to the iseven function to check if it is divisible by 2, and prints the result for each iteration.

How was this tutorial?