Type object is not subscriptable ошибка

On Career Karma, learn the cause of and the solution to the common TypeError: ‘type’ object is not subscriptable Python error.

“type” is a special keyword in Python that denotes a value whose type is a data type. If you try to access a value from an object whose data type is “type”, you’ll encounter the “TypeError: ‘type’ object is not subscriptable” error.

This guide discusses what this error means and why you may see it. It walks you through an example of this error so you can learn how to fix the error whenever it comes up.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: ‘type’ object is not subscriptable

Python supports a range of data types. These data types are used to store values with different attributes. The integer data type, for instance, stores whole numbers. The string data type represents an individual or set of characters.

Each data type has a “type” object. This object lets you convert values to a particular data type, or create a new value with a particular data type. These “type” objects include:

  • int()
  • str()
  • tuple()
  • dict()

If you check the “type” of these variables, you’ll see they are “type” objects:

The result of this code is: “type”.

We cannot access values from a “type” object because they do not store any values. They are a reference for a particular type of data.

An Example Scenario

Build a program that displays information about a purchase made at a computer hardware store so that a receipt can be printed out. Start by defining a list with information about a purchase:

purchase = type(["Steelseries", "Rival 600 Gaming Mouse", 69.99, True])

The values in this list represent, in order:

  • The brand of the item a customer has purchased
  • The name of the item
  • The price of the item
  • Whether the customer is a member of the store’s loyalty card program

Next, use print() statements to display information about this purchase to the console:

print("Brand: " + purchase[0])
print("Product Name: " + purchase[1])
print("Price: $" + str(purchase[2]))

You print the brand, product name, and price values to the console. You have added labels to these values so that it is easy for the user to tell what each value represents.

Convert purchase[2] to a string using str() because this value is stored as a floating point number and you can only concatenate strings to other strings.

Next, check to see if a user is a member of the store’s loyalty card program. You do this because if a customer is not a member then they should be asked if they would like to join the loyalty card program:

if purchase[3] == False:
	    print("Would you like to join our loyalty card program?")
else:
	    print("Thanks for being a member of our loyalty card program. You have earned 10 points for making a purchase at our store.")

If a user is not a member of the loyalty card program, the “if” statement runs. Otherwise, the else statement runs and the user is thanked for making a purchase.

Run our code and see if it works:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	     print("Brand: " + purchase[0])
TypeError: 'type' object is not subscriptable

Our code returns an error.

The Solution

Take a look at the offending line of code:

print("Brand: " + purchase[0])

The “subscriptable” message says you are trying to access a value using indexing from an object as if it were a sequence object, like a string, a list, or a tuple. In the code, you’re trying to access a value using indexing from a “type” object. This is not allowed.

This error has occurred because you’ve defined the “purchase” list as a type object instead of as a list. To solve this error, remove the “type” from around our list:

purchase = ["Steelseries", "Rival 600 Gaming Mouse", 69.99, True]

There is no need to use “type” to declare a list. You only need to use “type” to check the value of an object. Run our code and see what happens:

Brand: Steelseries
Product Name: Rival 600 Gaming Mouse
Price: $69.99
Thanks for being a member of our loyalty card program. You have earned 10 points for making a purchase at our store.

The code prints out the information about the purchase. It also informs that the customer is a loyalty card member and so they have earned points for making a purchase at the store.

Conclusion

The “TypeError: ‘type’ object is not subscriptable” error is raised when you try to access an object using indexing whose data type is “type”. To solve this error, ensure you only try to access iterable objects, like tuples and strings, using indexing.

Now you’re ready to solve this error like a Python expert!

In this post, we will learn how to fix TypeError:object is not subscriptable error in Python. The TypeError is raised when trying to use an illegal operation on non subscriptable objects(set,int,float) or does not have this functionally. Python throws the TypeError object is not subscriptable if We use indexing with the square bracket notation on an object that is not indexable.

1.TypeError:object is not subscriptable Python


In this Python program example, accessing the integer variable values, accessing with the square bracket notation and since is not indexable.

number = 56789
print( number[0])

Output

print( number[0])
TypeError: 'int' object is not subscriptable

Solution TypeError:object is not subscriptable Python

We have to access the integer variable without index notation.Let us understand with the below example

number = 56789
print( ‘The value is :’,number)

Output

  • TypeError:NoneType object is not subscriptable
  • ValueError:Cannot convert non-finite values (NA or inf) to integer
  • Fix ValueError: could not convert string to float
  • Fixed Typeerror: nonetype object is not iterable Python
  • ValueError:Cannot convert non-finite values (NA or inf) to integer

2.TypeError:object is not subscriptable set


We can’t access the set element by using the index notation.Running the below code will throw TypeError.To solve this error We have to use for loop to iterate over the set and display a single value.The Python object strings, lists, tuples, and dictionaries are subscribable their elements can be accessed using the index notation.

mySet = {3,6,9,12,15,18,121}
print(mySet[0]) 

Output

print(mySet[0])
TypeError: 'set' object is not subscriptable

Solution object is not subscriptable set

In this example we have for loop to iterate over the set and display each element in the set.

mySet = {3,6,9,12,15}
for inx in mySet:
print(inx,end=”,”)

Output

3.TypeError:object is not subscriptable Pandas


In this example, we are finding the sum of Pandas dataframe column “Marks” that has int type. While applying the Lambda function on the ‘Marks’ column using index notation or subscript operator and encountering with TypeError: ‘int’ object is not subscriptable in Pandas.

import pandas as pd
 
data = {
    'Name': ['Jack', 'Jack', 'Max', 'David'],
    'Marks':[97,97,100,100],
    'Subject': ['Math', 'Math', 'Math', 'Phy']
}
 
dfobj = pd.DataFrame(data)
print(dfobj.dtypes)
 
MarksGross = lambda x: int(x[1])
dfobj.Marks = dfobj.Marks.apply(MarksGross)

Print(dfobj.Marks.sum())

Output

  MarksGross = lambda x: int(x[1])
TypeError: 'int' object is not subscriptable

4. How to fix TypeError: int object is not Subscriptable Pandas


To solve Type Error with Pandas dataframe, We have not applied the lambda function using index notation instead use int(x) pass value of x inside () brackets.

import pandas as pd
 
data = {
    'Name': ['Jack', 'Jack', 'Max', 'David'],
    'Marks':[97,97,100,100],
    'Subject': ['Math', 'Math', 'Math', 'Phy']
}
 
dfobj = pd.DataFrame(data)
print(dfobj.dtypes)
 
MarksGross = lambda x: int(x)
dfobj.Marks = dfobj.Marks.apply(MarksGross)

print(dfobj.Marks.sum())

Output

Name       object
Marks       int64
Subject    object
dtype: object
394

Object Is Not Subscriptable

Overview

Example errors:

TypeError: object is not subscriptable

Specific examples:

  • TypeError: 'type' object is not subscriptable
  • TypeError: 'function' object is not subscriptable
Traceback (most recent call last):
  File "afile.py", line , in aMethod
    map[value]
TypeError: 'type' object is not subscriptable

This problem is caused by trying to access an object that cannot be indexed as though it can be accessed via an index.

For example, in the above error, the code is trying to access map[value] but map is already a built-in type that doesn’t support accessing indexes.

You would get a similar error if you tried to call print[42], because print is a built-in function.

Initial Steps Overview

  1. Check for built-in words in the given line

  2. Check for reserved words in the given line

  3. Check you are not trying to index a function

Detailed Steps

1) Check for built-in words in the given line

In the above error, we see Python shows the line

This is saying that the part just before [value] can not be subscripted (or indexed). In this particular instance, the problem is that the word map is already a builtin identifier used by Python and it has not been redefined by us to contain a type that subscripts.

You can see a full list of built-in identifiers via the following code:

# Python 3.0
import builtins
dir(builtins)

# For Python 2.0
import __builtin__
dir(__builtin__)

2) Check for instances of the following reserved words

It may also be that you are trying to subscript a keyword that is reserved by Python True, False or None

>>> True[0]
<stdin>:1: SyntaxWarning: 'bool' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not subscriptable

3) Check you are not trying to access elements of a function

Check you are not trying to access an index on a method instead of the results of calling a method.

txt = 'Hello World!'

# Incorrectly getting the first word
>>> txt.split[0]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable

# The correct way
>>> txt.split()[0]

'Hello'

You will get a similar error for functions/methods you have defined yourself:

def foo():
    return ['Hello', 'World']

# Incorrectly getting the first word
>>> foo[0]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

# The correct way
>>> foo()[0]
'Hello'

Solutions List

A) Initialize the value

B) Don’t shadow built-in names

Solutions Detail

A) Initialize the value

Make sure that you are initializing the array before you try to access its index.

map = ['Hello']
print(map[0])

Hello

B) Don’t shadow built-in names

It is generally not a great idea to shadow a language’s built-in names as shown in the above solution as this can confuse others reading your code who expect map to be the builtin map and not your version.

If we hadn’t used an already taken name we would have also got a much more clear error from Python, such as:

>>> foo[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

But don’t just take our word for it: see here

Further Information

  • Python 2: Subscriptions
  • Python 3: Subscript notation

@Gerry

comments powered by

Понравилась статья? Поделить с друзьями:
  • Type mismatch vba excel ошибка
  • Type hidden как изменить
  • Type error takes no arguments
  • Type error python что это
  • Type error js примеры