How to Fix TypeError: 'map' Object Is Not Subscriptable in Python
-
Cause of the
TypeError: 'map' object is not subscriptable
Error in Python -
Fix the
TypeError: 'map' object is not subscriptable
Error in Python
Every programming language encounters many errors. Some occur at the compile time, some at run time.
This article will discuss the TypeError: 'map' object is not subscriptable
, a sub-class of TypeError
. We encounter a TypeError
when we try to perform an operation incompatible with the type of object.
Cause of the TypeError: 'map' object is not subscriptable
Error in Python
Python 2 Map Operations in Python 3
In Python 2, the map()
method returns a list. We can access the list’s elements using their index through the subscriptor operator []
.
In Python 3, the map()
method returns an object which is an iterator and cannot be subscripted. If we try to access the item using the subscript operator []
, the TypeError: 'map' object is not subscriptable
will be raised.
Example Code:
# Python 3.x
my_list = ["1", "2", "3", "4"]
my_list = map(int, my_list)
print(type(my_list))
my_list[0]
Output:
#Python 3.x
<class 'map'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-07511913e32f> in <module>()
2 my_list = map(int, my_list)
3 print(type(my_list))
----> 4 my_list[0]
TypeError: 'map' object is not subscriptable
Fix the TypeError: 'map' object is not subscriptable
Error in Python
Convert the Map Object to List in Python 3
If we convert the map object to a list using the list()
method, we can use the subscript operator/list methods.
Example Code:
# Python 3.x
my_list = ["1", "2", "3", "4"]
my_list = list(map(int, my_list))
print(my_list[0])
Output:
#Python 3.x
1
Use the for
Loop With Iterator in Python 3
We can access the items in the iterator using a for
loop. It calls the __next__()
method at the back and prints all the values.
Example Code:
# Python 3.x
my_list = ["1", "2", "3", "4"]
my_list = list(map(int, my_list))
for i in my_list:
print(i)
Output:
#Python 3.x
1
2
3
4
I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.
LinkedInRelated Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python