Python: Map f to List

By Xah Lee. Date: . Last updated: .

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 Function of Multi-Args to Lists

map(f, li1, li2, etc)

Apply f of multi-args to all lists in parallel.

e.g.

map(f, [1,2,3], [a,b,c])

returns

[f(1,a), f(2,b), f(3,c)]

  • 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"])

Python, Data Structure

Python, Loop