52

This is my code

def fahrenheit(T):
    return ((float(9)/5)*T + 32)

temp = [0, 22.5, 40,100]
F_temps = map(fahrenheit, temp)

This is mapobject so I 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 that my solution was possible with Python 2.7,how to change this with 3.5?

voidpro
  • 1,652
  • 13
  • 27
MishaVacic
  • 1,812
  • 8
  • 25
  • 29

1 Answers1

103

You have to turn the map into a list or tuple first. To do that,

print(list(F_temps))

This is because maps are lazily evaluated, meaning the values are only computed on-demand. Let's see an 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

When you use map in a for loop, the loop automatically calls next for you, and treats the StopIteration error as the end of the loop. Calling list(mymap) forces all the map values to be evaluated.

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

However, since our evaluate function has no return value, result is simply [None, None, None]

codelessbugging
  • 2,849
  • 1
  • 14
  • 19
  • 8
    I find when I do this **the map gets zeroed out.** Meaning execute the print line above twice and you'll get an empty list the second time. This happens for me both on the command line and in jupyter. I assume this is because the map gets executed. Any ideas? – Kiki Jewell Sep 05 '17 at 20:16
  • @Kiki Jewell Try: print(list(map(fahrenheit, temp))) – spacedustpi Aug 21 '18 at 14:53
  • @spacedustpi This is the best we can do for printing a map in python - need `list(map(..))` ? – WestCoastProjects Dec 30 '18 at 20:12
  • Yes, the map gets zeroed out because it is intended for a single use only. However, if you wish to save the results, save the list itself. Then you can reprint it or access its elements as many times as you want. This is similar to the behavior of Streams in Java: you can only use the Stream once, after that you need to create a new stream. For the example above `result = list(mymap)` - to reprint just do `print(result)` – George Smith Feb 10 '20 at 18:30