Python map - How to make a list from a list

Python map makes a list from a list.

def hello(name):
    return 'Hello, ' + name + '.'


a = ['Alice', 'Bob']

b = map(hello, a)

print(b)
# <map object at 0x10c97ce50>

for i in b:
    print(i)

# Hello, Alice.
# Hello, Bob.

The first argument of map is a function and the second is a list. The first argument is only function name. hello() is incorrect and should be removed round brackets.

Python map returns a map object and each item can be accessed in for-loop statement.

def plus_one(n):
    return n + 1


a = [1, 2, 3, 4, 5]

b = map(plus_one, a)

print(b)
# <map object at 0x10cfdef40>

for i in b:
    print(i)

# 2
# 3
# 4
# 5
# 6

Python map example: Quadratic function

def f(x):
    return x * x


a = [-2, -1, 0, 1, 2, 3]
b = map(f, a)
c = list(b)

print(c)  # [4, 1, 0, 1, 4, 9]

Python map creates the map object from the integer list.

  • -2 -> 4
  • -1 -> 1
  • 0 -> 0
  • 1 -> 1
  • 2 -> 4
  • 3 -> 9

Python Tips

Python Tutorial