Python: Map, Filter, List
Map Function to List
map(f, list)
-
Apply function f to all items in list. Return a iterator of the result.
Does not modify the original list
Note: python 2,
map
,filter
, return a list. In python 3, they return a iterator object that represent the list.def ff(nn): return nn + 1 xx = [1, 2, 3, 4] print(list(map(ff, xx)) == [2, 3, 4, 5])
map(f, li1, li2, li3 …)
-
Apply f to all lists in parallel.
That is, first item of result would be
f(e1, e2, e3)
where its args are first elemet of each list. f should take same number args as there are lists. All lists must have same number of items (if short,None
is used). Return the new iterator.def ff(x1, x2): return str(x1) + str(x2) s1 = [1, 2, 3] s2 = ["a", "b", "c"] print(list(map(ff, s1, s2)) == ["1a", "2b", "3c"])
Filter List
filter(f, list)
-
Return a new iterator, such that
f(item)
returnsTrue
.# return True if divisible by 2 def ff(n): return n % 2 == 0 aa = [0, 1, 2, 3, 4, 5] bb = filter(ff, aa) print(list(bb) == [0, 2, 4])