0

Given a map of simple integers:

this_map = map(int, input().split())
2 4 1 3 5

How do I print this_map in reverse order? I can print each item with a simple for loop but printing the thing in reverse format requires indexing and this is not possible through standard procedure.

for item in this_map[::-1]:
    print(item)

TypeError: 'map' object is not subscriptable

A similar post on using enumerate() exists but how do I use it here to add indexes?

Note: I'm using Python 3.6

shiv_90
  • 1,025
  • 3
  • 12
  • 35

4 Answers4

2

Just use reversed:

this_map = map(int, reversed("2 4 1 3 5".split()))
for item in this_map:
    print(item)
Netwave
  • 40,134
  • 6
  • 50
  • 93
2

Your example didn't work because map() behaves differently in Python 2 vs Python 3. In Python 2 it returns a list, but in Python 3 it returns a special map object.

You can convert it to a list by calling list() on it:

this_map = list(this_map)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

Have you tried this:

for i in reversed(this_map):
    print(i)
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

Just convert the map into a list first

this_map = list(map(int, input().split()))
for item in this_map[::-1]:
    print(item)
Sudarshan
  • 938
  • 14
  • 27