Python: Map Function to List

By Xah Lee. Date: . Last updated: .

Map Function to List

map(f, list)
Applies function f to all elements 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.
Return a list represented by iterator_obj.
def ff(nn):
    return nn+1

bb = map(ff, [1,2,3,4])
# <map object at 0x10ad77cf8>

print( list(bb) )
# [2, 3, 4, 5]
map(f, li1, li2, li3 )
Applies f to all lists in parallel. That is, first element 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 elements (if short, None is used). Return the new iterator.
def ff(x1, x2, x3):
    return str(x1)+ str(x2) + str(x3)

print( list(map(ff, [1, 2, 3], ["a", "b", "c"], [4, 5, 6])) )
# ['1a4', '2b5', '3c6']

Filter List

filter(f, list)
Return a new iterator, such that f(element) returns True.
# return True if divisible by 2
def ff(n): return n % 2 == 0

aa = range(11)

bb = filter( ff, aa)

# [0, 2, 4, 6, 8, 10]

Python List, Tuple, Dictionary



Text Processing