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
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
Output
Retrieve the documentation string for the is_even function in Python
Explanation
- The code accesses the
__doc__attribute of theis_evenfunction, 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_evenis defined with a docstring, this will return that string; otherwise, it will returnNone. - This practice is common in Python to enhance code readability and provide guidance to users of the function.
Output
Retrieve and display the documentation string of the is_even function in Python.
Explanation
- The code uses the built-in
printfunction to output information to the console. is_even.__doc__accesses the documentation string (docstring) of theis_evenfunction, 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_evenis not defined, this will raise aNameError. - The output will be
Noneif the function does not have a docstring.
Output
2 Point of views
Function to Determine if a Given Integer is Even or Odd
Explanation
- Defines a function
is_eventhat 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.
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
powertakes two parameters,a(the base) andb(the exponent). - It uses the exponentiation operator
**to computearaised to the power ofb. - The result is returned as the output of the function.
- This function can handle both integer and floating-point numbers for
aandb. - It can be used in mathematical calculations where exponentiation is required.
This code snippet demonstrates how to calculate the power of a number using a function.
Explanation
- The function
poweris called with an argument of2, indicating that the base number is2. - The code likely computes
2raised 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
powerfunction. - This snippet is useful for understanding how to utilize functions for mathematical operations in Python.
Output
This Python function demonstrates the use of default arguments for exponentiation.
Explanation
- The function
powertakes two parameters,aandb, 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
araised to the power ofbusing 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.
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
powerfunction 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.
Output
Understanding the Use of Positional Arguments in a Python Function Call
Explanation
- The function
poweris called with two positional arguments:2and3. - The first argument
2is assigned to the first parameter of the function, while the second argument3is 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
2as the base and3as the exponent ifpoweris defined accordingly. - If the function
poweris not defined to accept two parameters, an error will occur.
Output
Demonstrating the use of keyword arguments in a function call in Python
Explanation
- The function
poweris called with keyword arguments, wherebis set to 3 andais 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
poweris defined to accept parametersaandbfor this call to work correctly.
Output
*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
multiplytakes two parameters,aandb, which represent the numbers to be multiplied. - It returns the product of
aandbusing 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.
This code snippet demonstrates how to multiply two numbers using a function call in Python.
Explanation
- The function
multiplyis called with two arguments,2and3. - 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.
Output
This function multiplies three input numbers and returns the result.
Explanation
- The function
multiplytakes three parameters:a,b, andc. - 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.
This code snippet demonstrates how to call a function to multiply multiple numbers together.
Explanation
- The function
multiplyis invoked with three arguments: 2, 3, and 4. - It is expected that the
multiplyfunction will return the product of these numbers. - The result of the multiplication will depend on the implementation of the
multiplyfunction, which is not shown here. - This snippet illustrates the concept of passing multiple parameters to a function in Python.
Output
This function multiplies an arbitrary number of arguments and returns the product.
Explanation
- The function
multiplyaccepts a variable number of arguments using*args, allowing for flexibility in input. - It initializes a variable
productto 1, which will hold the cumulative product of the input values. - A for loop iterates through each argument in
args, multiplying each value withproduct. - The function prints the
argstuple to show the input values received. - Finally, it returns the computed product of all the input arguments.
Demonstrating the usage of a multiply function with varying arguments in Python
Explanation
- The code calls a function named
multiplywith 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
multiplyfunction. - This snippet highlights the flexibility of Python functions in accepting variable numbers of arguments.
Output
This function calculates the product of an arbitrary number of input values.
Explanation
- The function
multiplyaccepts a variable number of arguments using the*madhusyntax, allowing for flexibility in input. - It initializes a variable
productto 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 theproductvariable. - The function prints the original input values and returns the final product after the loop completes.
This code snippet demonstrates how to print the result of multiplying multiple numbers using a function.
Explanation
- The
printfunction is used to output the result of themultiplyfunction. - The
multiplyfunction takes a variable number of arguments (in this case, the numbers 1 through 9). - The code assumes that the
multiplyfunction 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
multiplyfunction.
Output
Dynamically handle multiple keyword arguments in a Python function
Explanation
- The function
displayaccepts 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
kwargsusing theitems()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 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
Output
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 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
Output
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
Lis initialized with three integer elements: 1, 2, and 3. - The
appendmethod is called on the listLto add the integer 4 to the end of the list. - The
printfunction outputs the result of theappendmethod, which isNone, sinceappendmodifies the list in place and does not return a value. - After execution, the list
Lwill contain four elements: [1, 2, 3, 4].
Output
This code snippet demonstrates how to add an element to a list in Python.
Explanation
- A list
Lis initialized with three integer elements: 1, 2, and 3. - The
append()method is called on the listLto add the integer 4 as the last element. - The
print()function outputs the updated list, which now contains four elements: [1, 2, 3, 4].
Output
Variable Scope
Understanding the interaction between global and local variables in Python functions
Explanation
- The function
g(y)attempts to print the value ofx, which is defined as a global variable outside the function. - Inside the function,
xis accessed directly, demonstrating that global variables can be used within local scopes. - The function prints
xandx + 1, which will output5and6respectively when called withg(x). - After calling the function, the global variable
xis printed again, confirming its value remains unchanged at5. - This code snippet illustrates the concept of variable scope in Python, highlighting how global variables can be accessed within functions.
Output
Understanding variable scope and reference in Python functions
Explanation
- The function
f(y)attempts to increment a variablexthat is not defined within its local scope, leading to anUnboundLocalError. - The variable
xis defined globally with an initial value of 5 before the function is called. - When
f(x)is invoked, it passes the value ofx(5) to the parametery, butxinside 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 ofx, which remains 5, since the function does not modify it. - To fix the error,
xshould be declared asglobalinside the function if the intention is to modify the global variable.
Output
This Python function demonstrates variable scope and modification within a function.
Explanation
- The function
f(y)initializes a local variablexto 1 and increments it by 1, resulting inxbeing 2. - The
print(x)statement inside the function outputs the local value ofx, which is 2. - The variable
xoutside 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 ofx, which is still 5, demonstrating the concept of variable scope in Python.
Output
This code demonstrates function scope and variable manipulation in Python.
Explanation
- The function
f(x)takes an argumentx, increments it by 1, and prints the new value. - The original variable
xin 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
zand the originalx, illustrating the difference between local and global variable states.
Output
Nested Functions
This Python code demonstrates nested function definitions and their execution.
Explanation
- The outer function
fis defined, which contains another functionginside it. - The inner function
gprints a message when called, indicating its execution. - The outer function
falso prints a message when executed, showing its own execution context. - However, the inner function
gis not called withinf, so it will not execute unless explicitly invoked. - This structure illustrates the concept of function scope and encapsulation in 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.
Output
This code defines nested functions and demonstrates their invocation in Python.
Explanation
- The outer function
fcontains an inner functiong. - When
fis called, it executes the inner functiongfirst. - The inner function
gprints the message 'inside function g' to the console. - After
gis executed, control returns tof, which then prints 'inside function f'. - This showcases the concept of function nesting and scope in 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.
Output
Understanding variable scope and function nesting in Python through a simple function example
Explanation
- The function
g(x)takes an integer parameterxand defines a nested functionh()within it. - Inside
h(), the local variablexis reassigned to the string 'abc', but this does not affect thexing(x)due to Python's scoping rules. - The original
xis incremented by 1 before being printed, resulting in the output 'in g(x): x = 4'. - The nested function
h()is called, but its changes toxare local and do not impact the outer function'sx. - Finally, the function
g(x)returns the modified value ofx, which is 4, and this value is assigned toz.
Output
Understanding nested function behavior and variable scope in Python
Explanation
- The function
g(x)takes an integerx, increments it by 1, and prints the updated value. - Inside
g(x), a nested functionh(x)is defined, which also increments its parameterxby 1 and prints the result. - When
g(x)is called withx = 3, it incrementsxto 4, prints it, and then callsh(x)with the new value. - The nested function
h(x)increments its ownxto 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 valuezfromg(x)(which is 4), illustrating the difference between local and global variable scopes.
Output
Functions are 1st class citizens
Understanding the type and memory address of a function in Python
Explanation
- The
squarefunction takes a single argumentnumand returns its square by raising it to the power of 2. - The
type(square)function call returns the type of thesquarefunction, which is<class 'function'>. - The
id(square)function call returns the memory address of thesquarefunction, 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.
Output
This code snippet demonstrates variable reassignment and function referencing in Python.
Explanation
- The variable
xis reassigned to reference the functionsquare, which is assumed to be defined elsewhere in the code. - The
print(x)statement outputs the function object thatxnow references. - The
print(id(x))statement displays the memory address of the function object, confirming thatxpoints to the same object assquare. - The
print(x(3))statement calls the functionsquarewith an argument of3, outputting the result of the function execution.
Output
This code snippet demonstrates how to delete a function from the current namespace in Python.
Explanation
- The
delstatement is used to remove the specified object from the current scope. - In this case, the function
squareis 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
squarewill result in aNameError.
This code snippet demonstrates how to call a function to calculate the square of a number.
Explanation
- The function
squareis invoked with the argument3. - It is expected that the
squarefunction computes the value of 3 multiplied by itself. - The output will be
9, representing the square of the input number. - Ensure that the
squarefunction is defined elsewhere in the code for this call to work correctly.
Output
This code snippet demonstrates a function call with an argument in Python.
Explanation
- The code calls a function named
xand passes the integer3as an argument. - The function
xmust 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
xis not defined, this will raise aNameErrorindicating thatxis not recognized.
Output
This code snippet assigns the value of variable x to the variable square.
Explanation
- The variable
squareis created to store a value. - The value assigned to
squareis taken from another variablex. - This operation does not perform any calculations; it simply copies the value of
x. - The variable
xmust be defined prior to this line for the assignment to be valid.
This code snippet demonstrates how to store and invoke a function within a list in Python.
Explanation
- A list
Lis created containing integers and a function reference namedsquare. - The list is printed, displaying its contents, which include both numbers and the function.
- The last element of the list, which is the
squarefunction, is called with the argument3using 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.
Output
Understanding the behavior of sets with immutable data types in Python
Explanation
- The code attempts to create a set
scontaining a square, but the variablesquareis 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
squarewere defined as a hashable type (like an integer), the set would successfully contain that value. - The final line
sis likely intended to display the contents of the set, but without a definedsquare, it will raise an error.
Output
This code demonstrates the creation and invocation of a nested function in Python that returns another function.
Explanation
- The function
f()defines a nested functionx(a, b)that takes two parameters and returns their sum. - When
f()is called, it returns the nested functionx, which can then be invoked with two arguments. - The expression
f()(3, 4)callsf()to getx, and immediately callsxwith the arguments 3 and 4, resulting in 7. - The second
(3, 4)inf()(3, 4)(3, 4)is incorrect asxis 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.
Output
Python nested function closure returning inner function with parameter binding
Explanation
- The code defines a nested function structure where
f()returns the inner functionx, which itself returns another inner functiony - Function
yperforms multiplication of two parameters and serves as the final callable in the chain - When
f()is invoked, it returnsx, thenx(3,4)returnsy, and finallyy(3,4)executes the multiplication operation - The outer functions act as closures that encapsulate the inner function
ywhile 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
Output
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
Output
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
ais created that takes one argumentxand returnsxsquared (x**2). - The
printstatement calls the lambda function with the argument4, which computes4^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.
Output
This code defines a lambda function to sum two numbers and prints the result.
Explanation
- A lambda function named
ais created, which takes two parametersxandy. - The function returns the sum of
xandywhen called. - The
printstatement invokes the lambda function with arguments2and3. - The output of the function, which is
5, is displayed on the console.
Output
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
ais created, which takes one argumentx. - The function checks if the character 'a' is present in the input string
x. - The
printstatement calls the lambda function with the argument 'Madhu', which returnsFalsesince 'a' is not in 'Madhu'. - This code demonstrates the use of lambda functions for simple conditional checks in Python.
Output
This code defines a lambda function to determine if a number is even or odd.
Explanation
- A lambda function
ais created that takes one argumentx. - It uses a conditional expression to return 'even' if
xis 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.
Output
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
squarefunction takes an inputxand returns its square by raising it to the power of 2. - The
transformfunction accepts a functionfand a listL, iterating over each element inL. - For each element in
L, it applies the functionfand appends the result to theoutputlist. - Finally, the
outputlist is printed, showing the transformed values. - The list
Lcontains integers from 1 to 5, and thetransformfunction is called withsquareto compute their squares.
Output
This code applies a cubic transformation to each element in a list using a lambda function.
Explanation
- The
transformfunction takes two arguments: a function (in this case, a lambda function) and a listL. - The lambda function
lambda x: x**3defines 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.
Output
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
lambdafunction 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.
Output
This code snippet demonstrates how to apply a function to each element in a list using map and lambda in Python.
Explanation
- The
mapfunction applies a specified function to each item of the iterable (in this case, a list of numbers). - A
lambdafunction is defined to square each element (x**2). - The input list
[1, 2, 3, 4, 5]is passed tomap, 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.
Output
This code snippet labels each item in a list as 'even' or 'odd' based on its value.
Explanation
- A list
Lis defined containing integers from 1 to 5. - The
mapfunction applies a lambda function to each element of the listL. - 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.
Output
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
mapfunction 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.
Output
Filter
Filtering a list to retrieve numbers greater than five using a lambda function
Explanation
- The code defines a list
Lcontaining integers from 3 to 7. - It utilizes the
filterfunction to apply a condition defined by a lambda function. - The lambda function checks if each element
xin 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.
Output
This code filters a list to identify elements greater than five using a lambda function.
Explanation
- Utilizes the
mapfunction to apply a lambda expression to each element in the listL. - The lambda function checks if each element
xis greater than 5, returningTrueorFalse. - 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.
Output
Filtering a list to find fruits that contain the letter 'a'
Explanation
- The code defines a list of fruits named
fruitscontaining three items: 'apple', 'guava', and 'cherry'. - It uses the
filterfunction combined with alambdafunction to iterate through each fruit in the list. - The
lambdafunction 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'.
Output
This code checks if the letter 'a' is present in each fruit name from a list.
Explanation
- Utilizes the
mapfunction to apply a transformation to each element in thefruitslist. - The
lambdafunction takes each fruit namexand returnsTrueif 'a' is found in the name, otherwise returnsFalse. - 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().
Output
Reduce
Calculate the sum of a list of numbers using Python's functools module
Explanation
- The code imports the
functoolsmodule, 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,
xandy, and returns their sum. - The list
[1, 2, 3, 4, 5]is passed as the iterable toreduce(), which processes the elements cumulatively. - The final output is the total sum of the numbers in the list, which is 15.
Output
Filtering a list to retain only values greater than two using a lambda function
Explanation
- Utilizes the
filterfunction to apply a condition to each element in the list. - The
lambdafunction defines the condition, checking if each elementxis 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.
Output
This code filters a list to identify elements greater than two using a lambda function.
Explanation
- The
mapfunction applies a given function to all items in the input list. - A
lambdafunction is defined to check if each elementxis 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
mapfunction withlist().
Output
This code snippet finds the minimum value in a list using a functional programming approach.
Explanation
- Utilizes
functools.reduceto 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.
Output
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:
Output:
This function filters a list to return only unique elements.
Explanation
- The function
return_uniqueinitializes an empty listresto store unique items. - It iterates through each element
iin the input listL. - For each element, it checks if
iis not already inresbefore appending it, ensuring uniqueness. - Finally, the function returns the list
res, which contains only the unique elements fromL. - 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].
Output
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:
Output:
This code sorts a hyphen-separated string of colors in alphabetical order.
Explanation
- The function
sort_sequencetakes a stringseqas 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.
Output
Problem 3: Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.
Counting lowercase and uppercase characters in a string using Python function
Explanation
- The function
lower_uppertakes a string input and initializes counters for lowercase and uppercase characters - It iterates through each character in the string and uses
islower()andisupper()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
Output
Problem 4: Write a Python program to print the even numbers from a given list.
Function that filters even numbers from a list using modular arithmetic
Explanation
- The function
is_eventakes 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]
Output
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 :
This function checks if a number is a perfect number by summing its divisors.
Explanation
- The function
perfect_numtakes an integernumas input and initializes a variablesumto zero. - It iterates through all integers from 1 to
num - 1, checking if each integer is a divisor ofnum. - If a divisor is found, it adds that divisor to the
sum. - Finally, the function returns
Trueif thesumof the divisors equalsnum, indicating thatnumis a perfect number; otherwise, it returnsFalse. - The call
perfect_num(29)checks if 29 is a perfect number, which it is not, so the function will returnFalse.
Output
Problem-6: Write a Python function to concatenate any no of dictionaries to create a new one.
Merging multiple dictionaries into a single dictionary in Python
Explanation
- The function
merge_dictaccepts a variable number of dictionary arguments using*kwargs. - It initializes an empty dictionary
dto store the merged results. - The function iterates over each dictionary passed in
kwargsand updatesdwith the contents of each dictionary using theupdate()method. - Finally, it returns the merged dictionary containing all key-value pairs from the input dictionaries.
- The provided dictionaries
dic1,dic2, anddic3are merged by callingmerge_dict, resulting in a single dictionary with all entries combined.
Output
Problem-7 Write a python function that accepts a string as input and returns the word with most occurence.
Identify and print the most frequently used word in a given string
Explanation
- The function
most_usedtakes a stringsas input and splits it into individual words. - It uses a dictionary
dto 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.
Output
Problem-8 Write a python function that receives a list of integers and prints out a histogram of bin size 10
Create a histogram from a list of numbers by binning them into ranges
Explanation
- The function
histogramtakes a list of numbersLas input and calculates the minimum and maximum bins based on the values inL. - It initializes a dictionary
dto 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.
Output
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.
Calculate the nearest point from a list based on Euclidean distance in Python
Explanation
- Defines a function
shortest_distthat 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
sortedand retrieves the corresponding point from the original list. - Returns the point that is closest to the query point.
Output
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
bowtakes a list of stringsLas input, representing sentences. - It initializes a set
vocabto store unique words found in the sentences. - The first loop populates
vocabby 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 invocab. - Finally, the function prints the vocabulary and returns the frequency list.
Output
###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
mapfunction to apply a lambda function that takes three arguments (x, y, z) and returns their sum. - The
mapfunction 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.
Output
###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:
Output:
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
list1is defined containing integers from 1 to 6. - The
mapfunction is used to apply a lambda function to each element oflist1and its corresponding index fromrange(len(list1)). - The lambda function takes two arguments,
x(the element fromlist1) andy(the index), and computesx**y, which raisesxto the power ofy. - 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.
Output
###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
str1containing a sentence about the FIFA World Cup. - It uses the
filterfunction to iterate over each character instr1. - A lambda function checks if each character (converted to lowercase) is a vowel by comparing it to the string 'aeiou'.
- The
filterfunction 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.
Output
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_listis a list containing three sublists, each with integer elements. - The
functools.reducefunction is imported to apply a rolling computation to the items ofini_list. - A lambda function is used within
reduceto 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.
Output
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
employeesis 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.
Extracting full names of highly-skilled employees from a list of dictionaries
Explanation
- Utilizes
filterto create a subset of theemployeeslist, retaining only those with agradeof 'highly-skilled'. - Applies
mapto transform the filtered list by concatenating thefnameandlnamefields of each employee into a full name string. - The
lambdafunctions 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.
Output
Next in this series: Recursion in Python: From Basics to Advanced Problem Solving →

