In this tutorial, we will discuss the Python Lambda function. Python allows us to create or declare a function by def keyword.
Introduction of Python Lambda Function
Python Lambda is an anonymous function. What is an anonymous function?- The anonymous function contains a small piece of code. It imitates inline functions of C and C++, but it is not exactly an inline function. An anonymous function is defined without a name.
We can declare anonymous functions by using the lambda keyword. Even so, the Lambda functions can accept any number of arguments, but it can return only one value that will in the form of expression. It is useful when we need function objects.
lambda arguments : expression
#single arguments x = lambda a: a + 20 print(x(5)) #multiple arguments x = lambda a, b: a / b print(x(18, 6))
We are adding 20 to the argument a, and return the result: 25. and in multiple arguments example, we will get the output: 3.
Python lambda function with map():
The map() function in Python accepts a function and a list. It gives a new list which contains all modified items returned by the function for each item.
lst = (1,2,3,4,5,6) square_list = list(map(lambda x:x**2,lst)) print(square_list)
Output will be:
# Adding two lists using map and lambda numb1 = [1, 2, 3] numb2 = [4, 5, 6] result = map(lambda x, y: x + y, numb1, numb2) print(list(result))
The output will be:
Using Python lambda function with filter():
The Python filter() function takes in a function and takes a list as arguments. This presents an elegant way to filter out all the elements of any given sequence “sequence”, for which the function returns True.
Here, a small program example which returns the odd numbers:
# filter() with lambda() list = [5, 7, 21, 97, 54, 63, 77, 23, 75, 61] final_list = list(filter(lambda x: (x%2 != 0) , list)) print(final_list)
Output will be:
[5, 7, 97, 77, 23, 61]
Python Array in Python tutorial
What is the Python array?
Note: The items which are declared in the array, should be of the same type.
How to Adding Array Elements?
To add an element in an array list, we can use append() method.
vehicle = ["Ford", "sujuki", "BMW"] vehicle.append("Honda") print(Vehicle )
How to Removing Array Elements?
By the pop() method we can remove an element from the array. Let’s see this in a small example:
vehicle = ["Ford", "Suzuki", "BMW"] vehicle.pop("BMW") print(Vehicle )
The remove() method also use for removing a array element.
vehicle = ["Ford", "sujuki", "BMW"] vehicle.remove("BMW") print(Vehicle )
In this article, we have studied about the Python Lambda function and Python array with suitable examples. In coming one, we will discuss the class objects.
Thank You 🙂