The map()
function applies a given function to each item in an iterable (like a list or tuple) and returns a new iterable (map object). It’s useful for processing lists efficiently, transforming data, and applying functions without loops.
Example
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)
# Output: [1, 4, 9, 16]
This squares each number in the list.
Syntax
map(function, iterable)
- function → A function that processes each item.
- iterable → A list, tuple, or other sequence.
- Returns → A
map
object (convert it tolist()
ortuple()
to see results).
1. Doubling Each Number in a List
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)
# Output: [2, 4, 6, 8]
Transforms each number efficiently.
2. Converting Strings to Uppercase
words = ["hello", "world"]
uppercased = list(map(str.upper, words))
print(uppercased)
# Output: ['HELLO', 'WORLD']
Applies string methods to all elements.
3. Using map()
with Multiple Lists
a = [1, 2, 3]
b = [4, 5, 6]
summed = list(map(lambda x, y: x + y, a, b))
print(summed)
# Output: [5, 7, 9]
Pairs up elements and processes them together.
4. Converting List Items to Integers
values = ["10", "20", "30"]
numbers = list(map(int, values))
print(numbers)
# Output: [10, 20, 30]
Useful for handling numeric input from users.
5. Removing Spaces from Strings
names = [" Alice ", " Bob ", "Charlie "]
cleaned = list(map(str.strip, names))
print(cleaned)
# Output: ['Alice', 'Bob', 'Charlie']
Cleans whitespace efficiently.
Key Notes
- ✔ Applies a function to every element in an iterable.
- ✔ Faster and more readable than loops.
- ✔ Can work with multiple iterables.
- ✔ Returns a
map
object—convert it to alist()
ortuple()
to view results.
By using map()
, you can process large datasets efficiently, clean data, and transform lists with minimal code. 🚀