Skip to main content
Published on

map in Python

Share:

Introduction

The map function in Python is one of several built-in functions that promote a functional programming style. It allows you to apply a function to all items in an input (for example, a list), returning an iterator.

How Does map Work?

The map function takes two or more arguments: a function and one or more iterables. The passed function is applied to all items of the iterable.

def square(number):
  return number * number

numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result))  # [1, 4, 9, 16]

Why Use map?

1. Readability

Using map makes the code cleaner and easier to read, especially when compared to using loops.

2. Efficiency

map returns an iterator, which means it only computes the next value when needed.

3. Flexibility

With map, we can apply a function to multiple iterables. If we provide more than one iterable, the function must accept the same number of arguments as there are iterables.

names = ['alice', 'rita', 'peter']
initials = map(lambda name: name[0].upper(), names)
print(list(initials))  # ['A', 'R', 'P']

Alternatives to map

List Comprehensions

You can use list comprehensions to achieve a result similar to map.

numbers = [1, 2, 3, 4]
squares = [x*x for x in numbers]
print(squares)  # [1, 4, 9, 16]

Conclusion

The map function is an essential tool in any Python programmer's arsenal. It not only promotes readability and efficiency, but also offers an elegant way to transform data.

Happy coding!