Map Function
The built-in map() function applies a function to every item in an iterable and returns a map object (a lazy iterator). Syntax: map(function, iterable). Ex...
What is map()?
The built-in map() function applies a function to every item in an iterable and returns a map object (a lazy iterator). Syntax: map(function, iterable). Example: nums = [1, 2, 3, 4]; squares = list(map(lambda x: x**2, nums)) gives [1, 4, 9, 16]. The map object is consumed once, so if you need the result multiple times, convert it to a list. map() does not modify the original iterable; it produces new values.
map() with Multiple Iterables
map() can take multiple iterables and a function that accepts multiple arguments: result = list(map(lambda a, b: a + b, [1, 2, 3], [10, 20, 30])) gives [11, 22, 33]. The function receives one element from each iterable per call. map() stops at the shortest iterable, just like zip(). This is handy for element-wise operations on parallel lists without needing a zip() and loop.
map() vs List Comprehension
In modern Python, list comprehensions are generally preferred over map() for readability. [x**2 for x in nums] is arguably cleaner than list(map(lambda x: x**2, nums)). However, map() wins when the function already exists as a named function: list(map(str, nums)) is cleaner than [str(x) for x in nums]. For simple transformations with an existing function, map() is concise; for transformations requiring an inline lambda, list comprehensions are preferred.
Using map() with Built-in Functions
map() shines when used with built-in or already-defined functions: list(map(int, ["1", "2", "3"])) converts a list of strings to integers. list(map(str.upper, ["hello", "world"])) uppercases each string. list(map(abs, [-1, -2, 3])) takes the absolute value of each number. These are all cleaner with map() than with explicit lambdas, because the function already exists and naming it directly is both faster and more readable.
Worked Example
Read a line of space-separated numbers from the user and compute their squares: nums = list(map(int, input().split())); squares = list(map(lambda x: x**2, nums)); print(squares). Input "1 2 3 4" gives [1, 4, 9, 16]. The first map converts strings to integers; the second applies the squaring function. This two-step map pipeline is a classic competitive programming input pattern and an excellent way to demonstrate map() in practice.
Exam Tip
Key facts about map() for exams: it returns a lazy iterator, not a list (in Python 3). Iterating over a map object a second time yields nothing because it is already exhausted. What is the return type of map(func, lst)? It is a map object, a subtype of iterator. Another question: map([1,2,3], lambda x: x+1) — is the order correct? No — the function comes first, then the iterable. Getting the argument order wrong is a common error. Also know that map() with None as the function was valid in Python 2 but not Python 3.