This is not a Python Starter Tutorial but advanced Python Tips in a Random Order.
What is Lambda and why we use them?
‘def’ is used to build functions in Python. ‘Lambda’ is also another tool that can be used to build functions in Python.
Lambda is referred as a tool to create anonymous function. Please note that lambda takes only one expression. Whereas “def” is not restricted with one expression.
If we need more than one expression, multiple statements/lines, you need to use ‘def’ to create the function.
Some special uses of Lambda function:
#1 Two ways of finding a vowel from a input list.

We have a standard function ‘def’ that returns of input letter is vowel or not. Then using the ‘for’ loop, we call the ‘findVowels’ function to retrieve and display the vowels from the given input list.
Another simple method is to use ‘lambda’ function to get the same result.

The ‘filter’ uses the ‘lambda’ function and applies the input list to filter only the vowels using the above single line Python code. The main focus has to be given for ‘lambda’ and ‘filter’ to get the desired output here.
#2 Take another example where you want to get sum of all elements of a list.

The above standard sum logic can be achieved using ‘lambda’ with ‘reduce’ as given below:

The sum addition results of previous 2 input list elements are added to the next element. This continues till all the elements of the list. The repetitive operation of the lambda results over all the input list elements are done using the ‘reduce’ function.
#3 Let us look at another example.
We have 3 functions in the below code. add2x is adding x with 2, add3x is adding x with 3 and add4x is adding x with 4.
We have a dictionary with the values are the above 3 functions with appropriate key values (named as dict1 dictionary).

If we pass the key as ‘add3’ with input value 7, it supposed to execute the add3x function to add 3 and 7. Similarly we tried with add4 and 4 as inputs.
How we can use lambda for the above requirement?
We can use nested ‘lambda’ as given in the below Python code. Depends on the input dictionary key, appropriate ‘lambda’ function (whether to use ‘add2’, ‘add3’ or ‘add4’) is selected with given input number.

Cool, right?
#4 If you want to sort a set of dictionaries it’s better to use ‘lambda’ function.

Here we have sorted the dictionaries based on their ‘name’ values.
Similarly if we want to sort using their ‘country’ values, then we can change the above code to:

That’s all for now. See you in another tips article. Until then enjoy learning.