Sobes.tech
Junior

What is the map function in Python and how is it used?

sobes.tech AI

Answer from AI

map() applies the given function to each element of an iterable object and returns an iterator with the results of these calls.

Syntax:

# Takes two arguments: a function and an iterable object.
# Can take more than one iterable object.
map(function, iterable, ...)

Example of usage:

# Function to square a number
def square(x):
    return x * x

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Apply the function to each element of the list using map
# map returns an iterator, which needs to be converted to a list for output
squared_numbers = list(map(square, numbers))

# Output: [1, 4, 9, 16, 25]
print(squared_numbers)

Advantages:

  • Conciseness and readability of code for applying a function to each element.
  • Efficiency when working with large datasets, as it returns an iterator that generates values on demand.