
👉Python map() Function with Examples
The Python map() function is a powerful built-in function that applies a specified function to all the items in an iterable (like a list, tuple, or string) and returns a map object. This guide will explain its syntax, parameters, and various use cases with practical examples.
👉Python map() Function with Examples Syntax
python
map(function, iterator1, iterator2, …iteratorN)
👉Python map() Function with Examples Parameters:
- function: A required function that will be applied to each item in the iterable.
- iterator: One or more iterables (like lists, tuples, sets, etc.).
Return Value:
Returns a map object, which can be converted into a list, tuple, or other data structures for better readability.
👉How map() Function Works
The map() function applies the given function to each element in the iterable.
Example: Finding squares of numbers
python
def square(n):
return n * n
my_list = [2, 3, 4, 5, 6]
updated_list = map(square, my_list)
print(list(updated_list))
👉Output:
csharp
[4, 9, 16, 25, 36]
👉Using map() with Python Built-in Functions
The map() function can also be used with built-in functions like round().
Example: Rounding decimal values
python
my_list = [2.6743, 3.63526, 4.2325]
updated_list = map(round, my_list)
print(list(updated_list))
👉Output:
csharp
[3, 4, 4]
👉Using map() with Strings
map() can also process strings since they are iterable in Python.
Example: Converting string to uppercase
python
def myMapFunc(s):
return s.upper()
my_str = “hello world”
updated_list = map(myMapFunc, my_str)
print(“”.join(updated_list))
👉Output:
nginx
HELLO WORLD
👉Using map() with Multiple Iterators
You can pass multiple iterators to map().
Example: Adding values from two lists
python
def add(a, b):
return a + b
list1 = [1, 2, 3]
list2 = [4, 5, 6]
updated_list = map(add, list1, list2)
print(list(updated_list))
👉Output:
csharp
[5, 7, 9]
👉Using map() with Lambda Functions
Lambda functions are commonly used with map() for concise code.
Example: Multiplying numbers by 10
python
my_list = [2, 3, 4, 5]
updated_list = map(lambda x: x * 10, my_list)
print(list(updated_list))
👉Output:
csharp
[20, 30, 40, 50]
👉Using map() with Sets, Tuples, and Dictionaries
map() can also be applied to sets, tuples, and dictionaries.
👉Example with Tuple:
python
def myMapFunc(n):
return n.upper()
my_tuple = (‘php’, ‘java’, ‘python’)
updated_list = map(myMapFunc, my_tuple)
print(list(updated_list))
👉Output:
css
[‘PHP’, ‘JAVA’, ‘PYTHON’]
👉Python map() Function with Examples Summary
- The map() function simplifies repetitive operations on iterables.
- Ideal for data transformation, mathematical calculations, and string manipulation.
- Efficient and concise when combined with lambda functions.