DEV Community

Avnish
Avnish

Posted on • Originally published at pythonkb.com

How to Fix TypeError: 'map' Object Is Not Subscriptable in Python

Title : Python map object is not subscriptable

The error "TypeError: 'map' object is not subscriptable" occurs when you try to access elements of a map object using square brackets, which is not allowed because map objects are not subscriptable.

To fix this error, you can either convert the map object into a list using the list() function or use other methods like list comprehensions. Here's how you can do it:

  1. Using list() function to convert map object into a list:
payIntList = list(map(int, payList))
Enter fullscreen mode Exit fullscreen mode
  1. Using list comprehensions:
payIntList = [int(pi) for pi in payList]
Enter fullscreen mode Exit fullscreen mode

Both of these methods will convert each element of payList into an integer and store them in payIntList. You can then iterate over payIntList or perform any other operations you need.

Here's the code with an example:

payList = ['100', '200', '300']  # Example list of strings
payIntList = list(map(int, payList))  # Convert each element to int
for pi in payIntList:
    print(pi)  # Print each integer element
Enter fullscreen mode Exit fullscreen mode

or

payList = ['100', '200', '300']  # Example list of strings
payIntList = [int(pi) for pi in payList]  # Convert each element to int using list comprehension
for pi in payIntList:
    print(pi)  # Print each integer element
Enter fullscreen mode Exit fullscreen mode

Both of these snippets will output:

100
200
300
Enter fullscreen mode Exit fullscreen mode

Choose the method that fits your coding style and requirements best.

Top comments (0)