One of the nice features common to many of the latest programming languages like Python is support for lambda functions and functional programming techniques. In Python, this is implemented with the "map" method, a powerful method that takes a function and a list, performs the function individually on every element in the list and returns the result. What once would have been a tedious for-loop is now a one-liner.
- Skill level:
- Moderately Easy
Other People Are Reading
Open a terminal. In Windows by clicking "Start" followed by "Run" and then typing "cmd." In Mac OS X, click "Spotlight" and type "Terminal."
Type "python" into the terminal.
Type the following line to define a list:
list = [1,2,3,4,5,6,7,8,9,10]
Type the following line to multiply every element in the list by two:
map(lambda x: x * 2, list)
The "map" function performs a function on every element of a list. The "lambda" command defines a new, unnamed and temporary function for use in the map command and nowhere else. Combined, you can quickly create a new "times two" function and call it on every element in the list automatically.
Tips and warnings
- "Map" does not require a lambda function. Any valid Python function can be passed into "map." For example, try this to get all the ASCII values of a block of English text: map(ord, "Kevin")
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for