Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Hello, all. I don't know how to print map object with python 3. Have a look at my code.

def fahrenheit(T):

    return ((float(9)/5)*T + 32)

temp = [0, 22.5, 40,100]

F_temps = map(fahrenheit, temp)

Since it is a mapobject, I also tried something like this

for i in F_temps:

    print(F_temps)

<map object at 0x7f9aa050ff28>

<map object at 0x7f9aa050ff28>

<map object at 0x7f9aa050ff28>

<map object at 0x7f9aa050ff28>

I am not sure, but I think in Python 2.7, it is possible. How to change this with 3.5 ?

1 Answer

0 votes
by (26.4k points)

You can switch the map into a tuple or list first. To do that,

print(list(F_temps))

The reason is, it will take time to evaluate, which means the values are only computed on-demand.

For example:

def evaluate(x):

    print(x)

mymap = map(evaluate, [1,2,3]) # nothing gets printed yet

print(mymap) # <map object at 0x106ea0f10>

# calling next evaluates the next value in the map

next(mymap) # prints 1

next(mymap) # prints 2

next(mymap) # prints 3

next(mymap) # raises the StopIteration error

Here, the loop will automatically call next when you use the map in a for a loop. It also treats the StopIteration error as the end of the loop. When you call list(mymap), it forces all the map values to be evaluated

result = list(mymap) # prints 1, 2, 3

Since the evaluate function doesn't have any return value, the result would be [None,None,None]

Interested to learn more on Python topics? Come & Join: Python course

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
5 answers
0 votes
1 answer

Browse Categories

...