Hello Stackoverflow community)

Everyone writes that the fastest and most convenient division of a number into digits is the map() function for such a call: map(int, str(123)) (For example, they suggested this solution: Link to a question about this ). Next in that answer, the guy refers to the elements as a list:

 print "Happy" if b[0] + b[1] + b[2] == b[3] + b[4] + b[5] else "Unhappy" 

I do not go so writes the error of the appeal

 a = map(int, str(123)) a[1] Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'map' object is not subscriptable 

Tell me what to do? or maybe I'm doing something wrong?

    1 answer 1

    The link response refers to Python2. In the Python3 version, the map function does not return a list (as in Python2), but a special object of the map class of the same name. This object is iterable (that is, its elements can be traversed with for , and generally it can be accessed as with any iterator), but its elements cannot be accessed by index (which is what the error says).

    To get a list of numbers, you can explicitly bring this object to the list:

     digits = list(map(int, str(123))) print(digits) # [1, 2, 3] print(digits[0]) # 1 
    • Well, then how do I use the rendered map () in py3? - Olexie Polishchyk
    • @OlexiePolishchyk, the sample code in the answer is the same. - insolor
    • You got it right, thanks - Olexie Polishchyk