Mars Lee Mars Lee - 6 months ago 12
Python Question

How to use index to get the value from the result of map function by Python 3?

I try this:

def test(x):
return x**2

a = map(test,[1,2,3])


If I get the value like this:

for i in a:
print(a)


I will get
1,4,9
and this works perfectly.

But if I do this:
a[0]
. The error will be raised.

I know it is because the result of map function is map class:

type(map(test,[1,2,3])) == <class 'map'>


which is not subsciptable.

So how can I use the index to get the value of the result of map function?

Answer

Convert the map object into a list object:

a = list(map(test,[1,2,3]))

Then you can use list indices to access the individual elements.

Comments