๐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.
