Python map object is not subscriptable

PythonPython 3.x

Python Problem Overview


Why does the following script give the error:

payIntList[i] = payIntList[i] + 1000 TypeError: 'map' object is not subscriptable

payList = []
numElements = 0

while True:
        payValue = raw_input("Enter the pay amount: ")
        numElements = numElements + 1
        payList.append(payValue)
        choice = raw_input("Do you wish to continue(y/n)?")
        if choice == 'n' or choice == 'N':
                         break

payIntList = map(int,payList)

for i in range(numElements):
         payIntList[i] = payIntList[i] + 1000
         print payIntList[i]

Python Solutions


Solution 1 - Python

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

Solution 2 - Python

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Solution 3 - Python

Don't need to use range for this problem in pypy3 or python3, so it is actually less code..

for i in payIntList: print ( i + 1000 )

and coincidentally matches RustyTom's comment in PhiHag's solution above. Note : Can not reference a map using array brackets [] in pypy3 or python3 or it will throw the same error.

payIntList[i] 

Map ref caused the error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstationView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonagfView Answer on Stackoverflow
Solution 3 - PythonJoseph PoirierView Answer on Stackoverflow