Question:
Write a single line of code to print squares of numbers till 15 using lambda, map and list comprehension
Program:
1 |
map(lambda x: x*x, range(15)) |
Explanation:
The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
The map function is the simplest one among Python built-ins used for functional programming. These tools apply functions to sequences and other iterables. The filter filters out items based on a test function which is a filter and apply functions to pairs of item and running result which is reduce.
So here the output of the anonymous function for squaring x when x ranges from 1 to 15 is recieved.
Output:
1 |
=> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196] |
Leave a Reply