-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_map_tutorial.py
More file actions
38 lines (30 loc) · 1.42 KB
/
15_map_tutorial.py
File metadata and controls
38 lines (30 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# What is map()?
# The map(function, iterable) function applies a specified function to each element of an iterable object (e.g., a list).
# 1. Simple example with a regular function
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
# Apply square to each number
squared_iterator = map(square, numbers)
# Important: map returns an iterator, not a list.
# To see the result, you need to convert it to a list (list)
squared_list = list(squared_iterator)
print(f"Squared numbers (via def): {squared_list}")
# 2. Using with lambda (most common case)
# We already learned lambdas, and map works perfectly with them.
doubled = list(map(lambda x: x * 2, numbers))
print(f"Doubled numbers (via lambda): {doubled}")
# 3. Working with multiple lists
# map can accept multiple iterable objects if the function accepts multiple arguments.
nums1 = [1, 2, 3]
nums2 = [10, 20, 30]
sums = list(map(lambda x, y: x + y, nums1, nums2))
print(f"Sums of elements from two lists: {sums}")
# 4. Converting data types
# Often map is used for quick conversion, e.g., converting a list of strings to a list of numbers.
string_numbers = ["1", "2", "3", "4"]
integers = list(map(int, string_numbers))
print(f"List of strings to numbers: {integers}")
# 5. Comparison with list comprehension
# Almost always map can be replaced with list comprehension, which is considered more "pythonic":
# [x ** 2 for x in numbers] — this is equivalent to list(map(square, numbers))