forked from WebJournal/journaldev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_map_example.py
More file actions
64 lines (49 loc) · 1.6 KB
/
python_map_example.py
File metadata and controls
64 lines (49 loc) · 1.6 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# function to be used with map()
def to_upper_case(s):
return str(s).upper()
# utility function for pretty print iterator elements
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
# map() with tuple
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)
# map() with list
map_iterator = map(to_upper_case, ['x', 'a', 'abc'])
print_iterator(map_iterator)
# converting map object to list, set etc.
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_list = list(map_iterator)
print(my_list)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(my_set)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(my_tuple)
# using lambda function with map
list_numbers = [1, 2, 3, 4]
map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)
# map() with multiple iterable arguments
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)
# map() with multiple iterable arguments of different sizes
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8, 9, 10)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)
# map() with function None
# map_iterator = map(None, 'abc')
# print(map_iterator)
# for x in map_iterator:
# print(x)
map_iterator = map(lambda x: x, 'abc')
print_iterator(map_iterator)