Monday, January 6, 2025
HomeComputer SciencePython map() function

Python map() function

The map() function in Python is a built-in function used to apply a given function to each item in an iterable (like a list, tuple, etc.) and return a new iterable (a map object) with the results.

Syntax

python
map(function, iterable, ...)
  • function: A function to apply to each element of the iterable.
  • iterable: One or more iterables to be processed.
  • If multiple iterables are passed, the function must accept as many arguments as there are iterables, and it is applied element-wise.

Returns

A map object, which is an iterator. You can convert it to a list, tuple, or another collection type as needed.

See also  Loops in Python - For, While and Nested Loops

Examples

Single Iterable

python
# Example: Square each number in a list
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)

# Convert to list to see the result
print(list(squared))
# Output: [1, 4, 9, 16, 25]

Multiple Iterables

python
# Example: Add corresponding elements of two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
summed = map(lambda x, y: x + y, list1, list2)

# Convert to list to see the result
print(list(summed))
# Output: [5, 7, 9]

Using a Predefined Function

python
# Example: Convert a list of strings to uppercase
def to_uppercase(s):
return s.upper()

strings = ['hello', 'world']
uppercase_strings = map(to_uppercase, strings)

print(list(uppercase_strings))
# Output: ['HELLO', 'WORLD']

Lazy Evaluation

The map() function doesn’t execute until explicitly iterated over:

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

# No computation happens here
print(squared)
# Output: <map object at 0x...>

# Iterating forces computation
print(list(squared))
# Output: [1, 4, 9]

Key Points

  • Performance: map() is often faster than list comprehensions for applying simple functions, as it doesn’t require the overhead of constructing a list in memory.
  • Readable Alternative: In some cases, list comprehensions are preferred for readability:
    python
    squared = [x**2 for x in numbers]
  • Compatibility: If you need compatibility across Python 2 and 3, be aware that map() in Python 3 returns a lazy iterator, whereas in Python 2, it directly returns a list.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Who is Nikocado Avocado?

Who is iCarly?

Who is Bre Tiesi?

Celebrities Born in 1983

Recent Comments

0
Would love your thoughts, please comment.x
()
x