Mars Lee Mars Lee - 2 years ago 78
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:

I will get
and this works perfectly.

But if I do this:
. 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download