After mastering how to write our own functions, we can quickly write functions on the fly by using the keyword, lambda.
The syntax is,
lambda value1, value2 : expression
Main keywords for the above syntax:
– lambda: to indicate it is a shorthand of a function declaration.
– argument: value1, value2, etc are the names of arguments.
– colon (:): to indicate beginning of the expression.
– expression: specifies what we wish the function to return.
Lambda functions allow us to write functions in quick and simplified way. However, it is not advisable to use it all the time.
raise_to_power = lambda x, y: x ** y raise_to_power(2,3)
Another example extracted from my exercise in DataCamp:
# Define echo_word as a lambda function: echo_word echo_word = (lambda word1, echo: word1 * echo) # Call echo_word: result result = echo_word('hey', 5) # Print result print(result) #Output: heyheyheyheyhey
If you run the above code at the Jupyter Notebook’s online, the output is,
To understand the idea of using lambda function, let us try to use the map() function.
map() function applies a function over an object such as a list. Use the lambda function to define the function that map() will use to process the object. See sample code below:
nums = [2,4,6,8,10] result = map(lambda a: a ** 2, nums) #Convert into a list and print list_result = list(result) print(list_result) #Output: [4, 16, 36, 64, 100]
The nums is a list. The map object that results from the call to map() is stored in the variable result. What you can do next is convert the map object into a list and print out the value. How to do so?
The line of code below converts map object into a list,
list_result = list(result)
and you can see the output of executing the above code, all the numbers in the nums list are power by 2. In another simple example of using map() function with lambda,
# Create a list of strings: spells spells = ["protego", "accio", "expecto patronum", "legilimens"] # Use map() to apply a lambda function over spells: shout_spells shout_spells = map(lambda item: item + '!!!', spells) # Convert shout_spells to a list: shout_spells_list shout_spells_list = list(shout_spells) # Convert shout_spells into a list and print it print(shout_spells_list)
By now, you will know what the output is. All items in the lists are concatenated with ‘!!!”. Now we try something new!
Below exercise extracted from DataCamp, I was trying to use a lambda function with filter() function. This filter() function offers a way to filter out elements from a list that do not satisfy certain criteria.
The question of the exercise:
In the filter() call, pass a lambda function and the list of strings, fellowship. The lambda function should check if the number of characters in a string member is greater than 6; use the len() function to do this. Assign the resulting filter object to result. Convert result to a list and print out the list.
# Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf'] # Use filter() to apply a lambda function over fellowship: result result = filter(lambda member: len(member) > 6, fellowship) # Convert result to a list: result_list result_list = list(result) # Convert result into a list and print it print(result_list) #Output: ['samwise', 'aragorn', 'boromir', 'legolas', 'gandalf']
The reduce() function is useful for performing some computation on a list and, unlike map() and filter(), returns a single value as a result. To use reduce(), you must import it from the functools module.
# Import reduce from functools from functools import reduce # Create a list of strings: stark stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon'] # Use reduce() to apply a lambda function over stark: result result = reduce(lambda item1, item2: item1 + item2, stark) # Print the result print(result) #Output: robbsansaaryabrandonrickon
I am not sure in what situation the reduce() function will be used. If I come across it next time, I will share about it.
Summary of the day:
- lambda function.
- map() function.
- filter() function.
- reduce() function from functools module.