Python map() Built in Function
The map() function in Python executes a specified function for each item in an iterable. The item is sent to the function as a parameter. The map() function returns a map object, which is an iterator that yields the results of applying the function to each item. The map object can be converted into a list, tuple, set, or other collection type.
Here are some examples of using map() function in Python:
Using map() with a single iterable
# This example applies the len() function to each element of a list and returns a list of lengths
words = ["apple", "banana", "cherry"]
lengths = list(map(len, words))
print(lengths)
# Output: [5, 6, 6]
Using map() with multiple iterables
# This example applies the pow() function to two lists of numbers and returns a list of powers
base = [2, 3, 4]
exponent = [1, 2, 3]
powers = list(map(pow, base, exponent))
print(powers)
# Output: [2, 9, 64]
Using map() with lambda functions
# This example uses a lambda function to square each element of a list and returns a list of squares
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2 , numbers))
print(squares)
# Output: [1 ,4 ,9 ,16]
Using map() with custom functions
# This example defines a custom function to add one to each element of a list and returns a list of incremented values
def add_one(n):
return n + 1
numbers = [10 ,20 ,30 ,40]
result = list(map(add_one ,numbers))
print(result)
# Output: [11 ,21 ,31 ,41]
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment