Perché viene mostrato questo errore in una funzione Python 'object is not subscriptable'?
This mainly happens with functions return different data types according to the parameters given
The best way to avoid this is to use type() function to determine the return value’s data type and act accordingly
- x = fun() #function whose return data type is unknown
- if type(x) == int:#if the return value is an integer
- #do this
- elif type(x) == str:#if the return value is a string
- #do this
If the error is occurred inside the function you need to check your code to ensure it’s working properly.
Più sull'errore non sottoscrivibile (TypeError)
Python lancia un TypeError se si cerca di accedere ad un oggetto non sottoscrivibile in un modo in cui si accede ad un oggetto stringa o array (o qualsiasi altro tipo di oggetto sottoscrivibile).
here a string object subscripted
- >>> x = 'this is subscriptable'
- >>> x[0]
- >>> 't'
some common non-subscriptable object types are int, float, bool and NoneType
- >>> y = 123 #an integer
- >>> y[0] # will result an error
- Traceback (most recent call last):
- File "", line 1, in
- y[0]
- TypeError: 'int' object is not subscriptable
- >>>
This type of errors happen when you use the same variable to store different data types throughout your code and you eventually lost track of the data type the variable currently has.
Solution is either to check the variable carefully throughout the code or to use different variables to store values with different data types if memory usage is not an issue.
example:
- >>> x = '10' #x is a string
- >>> print(x)
- 10
- >>> x = int(x) #x is now a int
- >>> print(x)
- 10
- >>> x[0] # will result an error
- Traceback (most recent call last):
- File "", line 1, in
- y[0]
- TypeError: 'int' object is not subscriptable
- >>>
Articoli simili
- How to fix “str” object is not callable when using set() function in Python 3.6.4
- What does 'str' object does not support item assignment' error mean in python?
- Perché questo errore viene durante il caricamento dei documenti per una patente di guida?
- Come risolvere il messaggio 'Status: Failure -Test fallito: Errore IO: The Network Adapter could not establish the connection' da Oracle 12