Type object is not subscriptable python ошибка

Typeerror: type object is not subscriptable error occurs while accessing type object with index. Actually only those python objects which implements __getitems__() function are subscriptable. In this article, we will first see the root cause for this error. We will also explore how practically we can check which object is subscriptable and which is not. At last but not least, we will see some real scenarios where we get this error. So let’s start the journey.

Typeerror: type object is not subscriptable ( Fundamental Cause) –

The root cause for this type object is not subscriptable python error is invoking type object by indexing. Let’s understand with some practical scenarios.

var_list=[1,2,3]
var=type(var_list)
var[0]

typeerror type object is not subscriptable root cause

typeerror type object is not subscriptable root cause

Here var is a type python object. In the place of same, the list is python subscriptable object. Hence we can invoke it via index. Moreover, Here is the implementation –

var_list=[1,2,3]
var=type(var_list)
var_list[0]

type object is not subscriptable python

type object is not subscriptable python

The best way to fix this error is using correct object for indexing. Let’s understand with one example.

type object is not subscriptable python example

type object is not subscriptable python example

The fix is calling var[0] in the place of var_type[0] . Here ‘var’ is the correct object. It is a ‘str’ type object which is subscriptible python object.

How to check python object is subscriptable ?

Most importantly, As I explained clearly, Only those object which contains __getitems__() method in its object ( blueprint of its class) is subscriptible. Let’s see any subscriptible object and its internal method-

print(dir(var))

The output is –

['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
 '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 
'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Firstly, As the internal method __getitem__() is available in the implementation of the object of var( list) hence it is subscriptible and that is why we are not getting any error while invoking the object with indexes. Hope this article is helpful for your doubt.

Similar Errors-

Typeerror int object is not subscriptable : Step By Step Fix

Typeerror nonetype object is not subscriptable : How to Fix ?

Thanks

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Список частых ошибок в Python и их исправление.

TypeError: object is not subscriptable

Ошибка, которая сообщает, что обращение идет к элементам не правильно. Возможно, это другой тип объекта, а не тот, который вам кажется. Проверить можно командой type().

Например, такое может быть, если это список (list), а в обращаетесь за элементом к словарю (dictionary).

TypeError: unsupported type for timedelta days component: str

Ожидается число, а передается в timedelta строка. Исправить просто, если уверены, что передается цифра, то достаточно явно преобразовать в число: int(days)

Failed execute: tuple index out of range

Означает что передаётся меньше данных, чем запрашивается.

ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package

venv/bin/python bot/bot.py
Traceback (most recent call last):
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package

Конфилкт имени файла и директории — они не должны быть здесь одинаковыми. Поменяйте название директории или имени файла.

ValueError: a coroutine was expected, got

Traceback (most recent call last):
File «test.py», line 41, in
asyncio.run(update.update_operations)
File «/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py», line 37, in run
raise ValueError(«a coroutine was expected, got {!r}».format(main))
ValueError: a coroutine was expected, got

Забыта скобки () у функции в команде asyncio.run(update.update_operations).

В чем смысл и причина ошибки

Ошибка «‘X’ object is not subscriptable» означает, что вы пытаетесь обратиться к объекту типа X по индексу, но этот тип не поддерживает обращение по индексу. Например, 1[0] не имеет смысла.

После первой итерации цикла переменная ways содержит значение [(2, 0), 5, 1, 4, 1, 0, 1]. Заметно, что добавлялись не кортежи, а просто числа. Код обращается к этим числам по индексу, что и приводит к нашей ошибке.

Почему не добавляются кортежи? Дело в сигнатуре метода extend:

extend(self, iterable):
    ...

Этот метод принимает iterable, итерирует и каждое полученное значение добавляет в список. В вашем примере он получает кортеж из двух чисел и добавляет в список эти числа.

Как добавить кортеж в список одним элементом

Проще всего будет использовать метод append, который принимает 1 объект.

ways.append((first_op(ways[ind][0]),  ind + 1))

Можно также создать новый кортеж или список из одного элемента, как рекомендуется в соседнем ответе.

# кортеж из одного элемента: (a,)
# запятая обязательна!
ways.extend( ( (first_op(ways[ind][0], ind + 1), ) )

# список из одного элемента: [a]
ways.extend( [ (first_op(ways[ind][0], ind + 1) ] )

“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!

Python throws error, ‘type’ object is not subscriptable, when we try to index or subscript an element of type type.

Consider this code –

print(list[0])

# TypeError: 'type' object is not subscriptable

The problem with this code is that list is a built-in function which converts a string into characters array. Here we are subscripting the list function as if it was a list array.

You may use this –

list = list("Captain America")
print(list[0])

This is perfectly valid but it should never be used. Never use built-in function names as variable names. Why? Check this post – ‘list’ object is not callable.

The correct way is this –

newList = list("Captain America")
print(newList[0])

    Tweet this to help others

According to Python documentation, there are many built-in types –

  • Boolean – bool
  • Numeric – int, float, complex
  • Iterator
  • Sequence – list, tuple, range
  • Text – str
  • Binary – bytes, bytearray, memoryview
  • Set – set, frozenset
  • Mapping – dict
  • Others

Built-in functions list

These are the built-in functions which will return either type or builtin_function_or_method as their type –

abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()

Functions with type as 'type'

Functions in the below list will return 'type' as their type and indexing or subscripting them will throw the error, ‘type’ object is not subscriptable. So check if you have used any of these functions in your code and subscripting them –

  • dict
  • slice
  • object
  • enumerate
  • staticmethod
  • int
  • str
  • bool
  • bytearray
  • filter
  • super
  • bytes
  • float
  • tuple
  • property
  • type
  • frozenset
  • list
  • range
  • classmethod
  • zip
  • map
  • reversed
  • complex
  • memoryview
  • set

This code example will show the type of all built-in functions –

print(type(abs))
print(type(dict))
print(type(help))
print(type(min))
print(type(setattr))
print(type(all))
print(type(dir))
print(type(hex))
print(type(next))
print(type(slice))
print(type(any))
print(type(divmod))
print(type(id))
print(type(object))
print(type(sorted))
print(type(ascii))
print(type(enumerate))
print(type(input))
print(type(oct))
print(type(staticmethod))
print(type(bin))
print(type(eval))
print(type(int))
print(type(open))
print(type(str))
print(type(bool))
print(type(exec))
print(type(isinstance))
print(type(ord))
print(type(sum))
print(type(bytearray))
print(type(filter))
print(type(issubclass))
print(type(pow))
print(type(super))
print(type(bytes))
print(type(float))
print(type(iter))
print(type(print))
print(type(tuple))
print(type(callable))
print(type(format))
print(type(len))
print(type(property))
print(type(type))
print(type(chr))
print(type(frozenset))
print(type(list))
print(type(range))
print(type(vars))
print(type(classmethod))
print(type(getattr))
print(type(locals))
print(type(repr))
print(type(zip))
print(type(compile))
print(type(globals))
print(type(map))
print(type(reversed))
print(type(__import__))
print(type(complex))
print(type(hasattr))
print(type(max))
print(type(round))
print(type(delattr))
print(type(hash))
print(type(memoryview))
print(type(set))

Live Demo

Open Live Demo

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!

Python throws error, ‘type’ object is not subscriptable, when we try to index or subscript an element of type type.

Consider this code –

print(list[0])

# TypeError: 'type' object is not subscriptable

The problem with this code is that list is a built-in function which converts a string into characters array. Here we are subscripting the list function as if it was a list array.

You may use this –

list = list("Captain America")
print(list[0])

This is perfectly valid but it should never be used. Never use built-in function names as variable names. Why? Check this post – ‘list’ object is not callable.

The correct way is this –

newList = list("Captain America")
print(newList[0])

    Tweet this to help others

According to Python documentation, there are many built-in types –

  • Boolean – bool
  • Numeric – int, float, complex
  • Iterator
  • Sequence – list, tuple, range
  • Text – str
  • Binary – bytes, bytearray, memoryview
  • Set – set, frozenset
  • Mapping – dict
  • Others

Built-in functions list

These are the built-in functions which will return either type or builtin_function_or_method as their type –

abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()

Functions with type as 'type'

Functions in the below list will return 'type' as their type and indexing or subscripting them will throw the error, ‘type’ object is not subscriptable. So check if you have used any of these functions in your code and subscripting them –

  • dict
  • slice
  • object
  • enumerate
  • staticmethod
  • int
  • str
  • bool
  • bytearray
  • filter
  • super
  • bytes
  • float
  • tuple
  • property
  • type
  • frozenset
  • list
  • range
  • classmethod
  • zip
  • map
  • reversed
  • complex
  • memoryview
  • set

This code example will show the type of all built-in functions –

print(type(abs))
print(type(dict))
print(type(help))
print(type(min))
print(type(setattr))
print(type(all))
print(type(dir))
print(type(hex))
print(type(next))
print(type(slice))
print(type(any))
print(type(divmod))
print(type(id))
print(type(object))
print(type(sorted))
print(type(ascii))
print(type(enumerate))
print(type(input))
print(type(oct))
print(type(staticmethod))
print(type(bin))
print(type(eval))
print(type(int))
print(type(open))
print(type(str))
print(type(bool))
print(type(exec))
print(type(isinstance))
print(type(ord))
print(type(sum))
print(type(bytearray))
print(type(filter))
print(type(issubclass))
print(type(pow))
print(type(super))
print(type(bytes))
print(type(float))
print(type(iter))
print(type(print))
print(type(tuple))
print(type(callable))
print(type(format))
print(type(len))
print(type(property))
print(type(type))
print(type(chr))
print(type(frozenset))
print(type(list))
print(type(range))
print(type(vars))
print(type(classmethod))
print(type(getattr))
print(type(locals))
print(type(repr))
print(type(zip))
print(type(compile))
print(type(globals))
print(type(map))
print(type(reversed))
print(type(__import__))
print(type(complex))
print(type(hasattr))
print(type(max))
print(type(round))
print(type(delattr))
print(type(hash))
print(type(memoryview))
print(type(set))

Live Demo

Open Live Demo

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • python error,
  • python-short

Понравилась статья? Поделить с друзьями:
  • Type mismatch vba word ошибка
  • Type mismatch vba excel ошибка runtime 13
  • Type mismatch in expression access ошибка
  • Txd workshop ошибка floating point
  • Txd workshop ошибка access violation at address 00000000