Question

a=['1','2','3']

map(int,a) can be exhausted using list to yield output:

list(map(int,a))

output: 1,2,3


a=['1','2','3']
b=['1','2']

How do I exhaust the following:

map(int,a,b)
Was it helpful?

Solution

If you want to convert each of the lists to a list of integers, you can do

a, b = ['1','2','3'], ['1','2']
print(list(map(lambda x: map(int,x), [a, b])))
# [[1, 2, 3], [1, 2]]

which can be assigned to a and b back, like this

a, b = map(lambda x: map(int,x), [a, b])

If you want to chain the elements, you can use itertools.chain, like this

from itertools import chain
print(list(map(int, chain(a,b))))
# [1, 2, 3, 1, 2]

Edit: if you want to pass more than iterable as arguments, then the function also has to accept that many number of parameters. For example,

a, b = [1, 2, 3], [1, 2, 3]
print(list(map(lambda x, y: x + y, a, b)))
# [2, 4, 6]

If we are passing three iterables, the function has to accept three parameters,

a, b, c = [1, 2, 3], [1, 2, 3], [1, 2, 3]
print(list(map(lambda x, y, z: x + y + z, a, b, c)))
# [3, 6, 9]

If the iterables are not of the same size, then the length of the least sized iterable will be taken in to consideration. So

a, b, c = [1, 2, 3], [1, 2, 3], [1, 2]
print(list(map(lambda x, y, z: x + y + z, a, b, c)))
# [3, 6]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top