C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: The map method passes all elements of the list to the lambda. It does this one at a time.
Result: We receive an iterable collection containing the elements of the list. All elements have had 1 added to their values.
Tip: The lambda is not required. A def-function may be passed to the map built-in method.
Python program that uses map
# An input list.
items = [1, 2, 3]
# Apply lambda to all elements with map.
for r in map(lambda x: x + 1, items):
print(r)
Output
2
3
4
Caution: This code creates a copy of the original list. Both exist in memory. This may be inefficient if you want to modify a list.
Python program that creates list with map
# Original list.
items = [7, 8, 9]
# Map into a new list.
items2 = list(map(lambda z: z * 2, items))
# Display two lists.
print(items)
print(items2)
Output
[7, 8, 9]
[14, 16, 18]
Here: We use map with a predicate method. Then we use sum() to count true results of the predicate.
Lambda: We use a lambda expression: this one receives a string parameter. It calls the startswith method.
And: They are counted by sum. Three of the four strings start with the substring "San" in the list.
Python program that sums result of map
# Cities.
names = ["San Jose", "San Francisco", "Santa Fe", "Houston"]
# Sum result of map.
count = sum(map(lambda s: s.startswith("San"), names))
# Count of cities starting with San.
print(count)
Output
3
However: Map does not care. It proceeds as far as it can, which is three elements.
Tip: The lambda here accepts two arguments. This is required when using two iterables.
Info: The first argument is the first list's element. And the second argument is from the other list.
Python program that uses two lists in map
# Two input lists.
a = [1, 2, 3]
b = [2, 3, 4, 5]
# Multiply elements of two lists together.
result = list(map(lambda x, y: x * y, a, b))
# Three elements are present.
print(result)
Output
[2, 6, 12]
Version 1: In this version of the code we invoke the map method, and loop over the results of map.
Version 2: We directly loop over a list, and use the same logic as version 1 but without the map in vocation.
Result: Calling map() was slower. Map() may be best reserved for situations where the clarity of code (not its speed) is more important.
Python program that times map, for-loop
import time
numbers = [5, 10, 15, 20, 30, 40]
print(time.time())
# Version 1: map.
for c in range(0, 1000000):
sum = 0
for i in map(lambda v: v + 20, numbers):
sum += i
print(time.time())
# Version 2: for-loop.
for c in range(0, 1000000):
sum = 0
for v in numbers:
sum += (v + 20)
print(time.time())
Output
1411254268.364547
1411254271.106704 map: 2.742 s
1411254272.373777 for-loop: 1.267 s