Notes

`map()` Function in Python [ English ]

< Prev Next >

map() Function in Python

1. Introduction

The map() function in Python is a built-in function used to apply a specified function to every element of an iterable (such as a list, tuple, or string). It returns an iterator containing the results after applying the function to each element.

The map() function is commonly used when the same operation needs to be performed on multiple elements of a sequence.

2. Syntax

map(function, iterable)

Parameters

  1. function A function that defines the operation to be performed on each element.

  2. iterable A sequence such as a list, tuple, or string whose elements will be processed.

Return Value

3. Basic Example

def square(n):
    return n * n

numbers = [1, 2, 3, 4]

result = map(square, numbers)

print(list(result))

Output

[1, 4, 9, 16]

Explanation

4. Using map() with a Lambda Function

A lambda function is an anonymous function used for short operations.

numbers = [1, 2, 3, 4]

result = map(lambda x: x * 2, numbers)

print(list(result))

Output

[2, 4, 6, 8]

Explanation

5. Example with Multiple Iterables

map() can also take multiple iterables as arguments.

a = [1, 2, 3]
b = [4, 5, 6]

result = map(lambda x, y: x + y, a, b)

print(list(result))

Output

[5, 7, 9]

Explanation

6. Example with String Conversion

numbers = [1, 2, 3, 4]

result = map(str, numbers)

print(list(result))

Output

['1', '2', '3', '4']

Explanation

7. Without map() vs With map()

Without map()

numbers = [1, 2, 3]
result = []

for n in numbers:
    result.append(n * 2)

print(result)

With map()

numbers = [1, 2, 3]
result = map(lambda x: x * 2, numbers)

print(list(result))

Advantage

8. Important Points

Example:

result = map(lambda x: x + 1, [1, 2, 3])
print(result)        # map object
print(list(result))  # actual values

9. Practical Example

prices = [100, 200, 300]

# Add 10% tax to each price
result = map(lambda x: x * 1.10, prices)

print(list(result))

Output

[110.0, 220.0, 330.0]

10. Summary

< Prev Next >