Python map and starmap functions

Python map and starmap functions

python map function


python map function
map(function, iterable, ...)

  • The map() function is used to apply a function to each item in the iterable.
  • We can also pass multiple iterables, but the function mentioned should also have that many arguments (e.g. two iterables means two arguments).
  • If multiple iterables given are of different lengths, the map iterator stops when the shortest iterable is exhausted.
  • The return type is a map object.
  • map object is an iterator.

python map function python map function

We can access the python map object, which is an iterator, in the following ways:

  • We can convert the map object to sequence objects like a list using a list() constructor and like a tuple using a tuple() constructor.
  • We can also iterate through the map object using a python for loop.
  • We can access the element in the map object using the next() function as well.

Example 1: Applying a function to all items in one iterable using map()

  • The square() function is defined to return the square the numbers.
  • In the map function, we are passing the square() function and list object.
  • The square() function is applied to all items in the list object.
  • The return type is a map object.
  • A map object is an iterator that contains the square of all items in the iterable (list object).
  • Convert the map object to a list using a list() constructor.
def square(x):
    return x*x

numbers = [1,2,3,4]
squares = map(square, numbers)

# Returns a map object
print(squares)
# output: <map object at 0x7f3c71350dd8>

print(type(squares))
# output: <class 'map'>

# converting map object to list() constructor
print(list(squares))
# output:
# [1, 4, 9, 16]

Example 2: Applying a lambda function to all items in one iterable using the map() function

numbers = [1,2,3,4]
squares = map(lambda x: x*x, numbers)

# Returns a map object
print(squares)
# output: <map object at 0x7f3c71350ef0>

print(type(squares))
# output: <class 'map'>

# converting map object to list() constructor.
list(squares)
# output:
# [1, 4, 9, 16]

# converting map object to tuple() constructor.
# need create new map object because previous map object (iterator) is at end 
squares = map(lambda x: x*x, numbers)
tuple(squares)
# output:
# (1, 4, 9, 16)

Example 3: Applying a function to two iterables of the same length using the map() function

  • Since two iterables are given, the function should contain two arguments.
  • The multiply(x, y) function will take the first argument x from the first iterable numbers1 and the second argument y from second iterable numbers2.
def multiply(x, y):
    return x*y

numbers1 = [1,2,3,4]
numbers2 = [2,4,6,8]

squares = map(multiply, numbers1, numbers2)

# converting map object to list() constructor.
list(squares)

# output:
# [2, 8, 18, 32]

Example 4: Applying a function containing one argument to two iterables using the map() function

  • This will raise a TypeError.
  • For two iterables, the function should contain two arguments.
def multiply(x):
    return x

numbers1 = [1,2,3,4]
numbers2 = [2,4,6,8]

squares = map(multiply, numbers1, numbers2)

# converting map object to list() constructor raise TypeError exception.
list(squares)

# output:
# TypeError: multiply() takes 1 positional argument but 2 were given

Example 5: Applying a function to more iterables of different lengths using the map() function

def multiply(x, y, z):
    return x*y*z

num1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num2 = [2, 4]
num3 = [2, 3, 4, 5, 6]

s = map(multiply, num1, num2, num3)

list(s)

# output:
# [4, 24]

Example 6: Iterating through a map object using a for loop

def square(x):
    return x*x

num1 = [1, 2, 3, 4]

square = map(square, num1)

for item in square:
    print(item)

# output:
# 1
# 4
# 9
# 16

Example 7: Accessing elements in the map object using the next() function

  • A map object is an iterator. So we can access the next element in the map object using the next() function.
def square(x):
    return x*x

numbers = [1, 2, 3, 4]

squares = map(square, numbers)

for item in squares:
    print(item)

print(next(s))
print(next(s))
print(next(s))
print(next(s))

# output:
# 1
# 4
# 9
# 16

# numbers list has 4 items, so print(next(s)) raise error
print(next(s))

# output:
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# StopIteration

Example 8: Applying a built-in function to an iterable (string) using the map() function

colors = ['red', 'blue', 'green']
uppers = list(map(str.upper, colors))

list(uppers)
# output:
# ['RED', 'BLUE', 'GREEN']

python starmap function


python starmap function
itertools.starmap(function, iterable)

The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). Roughly equivalent to:

def starmap(function, iterable):
    for args in iterable:
        yield function(*args)

# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
  • First, we have to import the itertools module.
  • The starmap method is supported by the itertools module only.
  • starmap(function, iterable) → The function and iterable are passed to the starmap method.
  • Items inside the iterable should also be iterable. Otherwise, it will raise a TypeError.
  • The return type is an itertools.starmap object.
  • The starmap object is an iterator.

We can access the starmap object, which is an iterator, in the following ways:

  • We can convert the starmap object to sequence objects like a list using a list() constructor or a tuple using a tuple() constructor.
  • We can also iterate through the map object using a for loop.
  • We can access the element in the starmap object using the next() function as well.

python starmap function python starmap function

Example 1: Applying a user-defined function to a list of tuples using starmap()

from itertools import starmap

numbers = [(1, 2), (2, 3)]

def multiply(x, y):
    return x * y

starmap_object = starmap(multiply, numbers)

print(starmap_object)
# output:
# <itertools.starmap object at 0x7f3c71363278>

# Converting map object to list using list()
list(starmap_object)
# output:
# [2, 6]

Example 2: Applying pow() to a list of tuples using starmap()

import itertools

starmap_object = itertools.starmap(pow, [(0,2), (1,2), (2,2)])

print(starmap_object)
# output:
# <itertools.starmap object at 0x7f3c71363390>

# converting starmap object to list by using list() constructor.
list(starmap_object)
# output:
# [0, 1, 4]

using map():

map_object = map(pow, [0,1,2], [2,2,2])
list(map_object)

# output:
# [0, 1, 4]

Example 3: If elements inside the iterable are not iterable, it will raise a TypeError

import itertools

starmap_object = itertools.starmap(lambda x: x**2, [1,2,3])
list(starmap_object)
# output:
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable


#### Example 4: Applying a lambda function to a list of tuples using starmap()

```python3
import itertools

starmap_object = itertools.starmap(lambda x,y: x+y, [(0,1), (1,2), (2,3)])
list(starmap_object)

# output:
# [1, 3, 5]

Example 5: Accessing items in the starmap object using a for loop

import itertools

starmap_object = itertools.starmap(lambda x, y: x + y, [(0, 1), (1, 2), (2, 3)])

for item in starmap_object:
    print(item)

# output:
# 1
# 3
# 5

Example 6: Accessing items in the starmap object using the next() method

  • A starmap object is an iterator. So we can access the next element in the map object using the next() function.
import itertools

starmap_object = itertools.starmap(lambda x,y: x+y, [(0,1), (1,2), (2,3)])

print(next(starmap_object))  # output:1
print(next(starmap_object))  # output:3
print(next(starmap_object))  # output:5