Ошибка typeerror int object is not subscriptable

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

Ошибка «‘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) ] )

TypeError: 'int' object is not subscriptable [Solved Python Error]

The Python error «TypeError: ‘int’ object is not subscriptable» occurs when you try to treat an integer like a subscriptable object.

In Python, a subscriptable object is one you can “subscript” or iterate over.

You can iterate over a string, list, tuple, or even dictionary. But it is not possible to iterate over an integer or set of numbers.

So, if you get this error, it means you’re trying to iterate over an integer or you’re treating an integer as an array.

In the example below, I wrote the date of birth (dob variable) in the ddmmyy format. I tried to get the month of birth but it didn’t work. It threw the error “TypeError: ‘int’ object is not subscriptable”:

dob = 21031999
mob = dob[2:4]

print(mob)

# Output: Traceback (most recent call last):
#   File "int_not_subable..py", line 2, in <module>
#     mob = dob[2:4]
# TypeError: 'int' object is not subscriptable

How to Fix the «TypeError: ‘int’ object is not subscriptable» Error

To fix this error, you need to convert the integer to an iterable data type, for example, a string.

And if you’re getting the error because you converted something to an integer, then you need to change it back to what it was. For example, a string, tuple, list, and so on.

In the code that threw the error above, I was able to get it to work by converting the dob variable to a string:

dob = "21031999"
mob = dob[2:4]

print(mob)

# Output: 03

If you’re getting the error after converting something to an integer, it means you need to convert it back to string or leave it as it is.

In the example below, I wrote a Python program that prints the date of birth in the ddmmyy format. But it returns an error:

name = input("What is your name? ")
dob = int(input("What is your date of birth in the ddmmyy order? "))
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Traceback (most recent call last):
#   File "int_not_subable.py", line 12, in <module>
#     dd = dob[0:2]
# TypeError: 'int' object is not subscriptable

Looking through the code, I remembered that input returns a string, so I don’t need to convert the result of the user’s date of birth input to an integer. That fixes the error:

name = input("What is your name? ")
dob = input("What is your date of birth in the ddmmyy order? ")
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Hi, John Doe,
# Your date of birth is 01
# Month of birth is 01
# And year of birth is 1970.

Conclusion

In this article, you learned what causes the «TypeError: ‘int’ object is not subscriptable» error in Python and how to fix it.

If you are getting this error, it means you’re treating an integer as iterable data. Integers are not iterable, so you need to use a different data type or convert the integer to an iterable data type.

And if the error occurs because you’ve converted something to an integer, then you need to change it back to that iterable data type.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Introduction

Some of the objects in python are subscriptable. This means that they hold and hold other objects, but an integer is not a subscriptable object. We use Integers used to store whole number values in python. If we treat an integer as a subscriptable object, it will raise an error. So, we will be discussing the particular type of error that we get while writing the code in python, i.e., TypeError: ‘int’ object is not subscriptable. We will also discuss the various methods to overcome this error.

What is TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. Let us understand with the help of an example:

Suppose we try to concatenate a string and an integer using the ‘+’ operator. Here, we will see a TypeError because the + operation is not allowed between the two objects that are of different types.

#example of typeError

S = "Latracal Solutions"
number = 4
print(S + number)

Output:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print(S + number)
TypeError: can only concatenate str (not "int") to str

Explanation:

Here, we have taken a string ‘Latracal Solutions” and taken a number. After that, in the print statement, we try to add them. As a result: TypeError occurred.

What is ‘int’ object is not subscriptable?

When we try to concatenate string and integer values, this message tells us that we treat an integer as a subscriptable object. An integer is not a subscriptable object. The objects that contain other objects or data types, like strings, lists, tuples, and dictionaries, are subscriptable. Let us take an example :

1. Number: typeerror: ‘int’ object is not subscriptable

#example of integer which shows a Typeerror

number = 1500
print(number[0])

output:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(number[0])
TypeError: 'int' object is not subscriptable

Explanation:

Here, we have taken a number and tried to print the through indexing, but it shows type error as integers are not subscriptable.

2. List: typeerror: ‘int’ object is not subscriptable

This TyperError problem doesn’t occur in the list as it is a subscriptable object. We can easily perform operations like slicing and indexing.

#list example which will run correctly

Names = ["Latracal" , " Solutions", "Python"]
print(Names[1])

Output:

Solutions

Explanation:

Here firstly, we have taken the list of names and accessed it with the help of indexing. So it shows the output as Solutions.

Daily Life Example of How typeerror: ‘int’ object is not subscriptable can Occur

Let us take an easy and daily life example of your date of birth, written in date, month, and year. We will write a program to take the user’s input and print out the date, month, and year separately.

#Our program begins from here

Date_of_birth = int(input("what is your birth date?"))

birth_date = Date_of_birth[0:2]

birth_month = Date_of_birth[2:4]

birth_year = Date_of_birth[4:8]

print(" birth_date:",birth_date)
print("birth_month:",birth_month)
print("birth_year:",birth_year)

Output:

what is your birth date?31082000
Traceback (most recent call last):
  File "C:/Users/lenovo/Desktop/fsgedg.py", line 3, in <module>
    birth_date = Date_of_birth[0:2] 
TypeError: 'int' object is not subscriptable

Explanation:

Here firstly, we have taken the program for printing the date of birth separately with the help of indexing. Secondly, we have taken the integer input of date of birth in the form of a date, month, and year. Thirdly, we have separated the date, month, and year through indexing, and after that, we print them separately, but we get the output ad TypeError: ‘int’ object is not subscriptable. As we studied above, the integer object is not subscriptable.

Solution of TypeError: ‘int’ object is not subscriptable

We will make the same program of printing data of birth by taking input from the user. In that program, we have converted the date of birth as an integer, so we could not perform operations like indexing and slicing.

To solve this problem now, we will remove the int() statement from our code and run the same code.

#remove int() from the input()

Date_of_birth = input("what is your birth date?")

birth_date = Date_of_birth[0:2]

birth_month = Date_of_birth[2:4]

birth_year = Date_of_birth[4:8]

print(" birth_date:",birth_date)
print("birth_month:",birth_month)
print("birth_year:",birth_year)

Output:

what is your birth date?31082000
 birth_date: 31
birth_month: 08
birth_year: 2000

Explanation:

Here, we have just taken the input into the string by just removing the int(), and now we can do indexing and slicing in it easily as it became a list that is subscriptable, so no error arises.

Must Read

Conclusion: Typeerror: ‘int’ object is not subscriptable

We have learned all key points about the TypeError: ‘int’ object is not subscriptable. There are objects like list, tuple, strings, and dictionaries which are subscriptable. This error occurs when you try to do indexing or slicing in an integer.

Suppose we need to perform operations like indexing and slicing on integers. Firstly, we have to convert the integer into a string, list, tuple, or dictionary.

Now you can easily the solve this python TypeError like an smart coder.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

We raise the TypeError: ‘int’ object is not subscriptable when trying to treat an integer type value like an array. Subscriptable objects in Python contain or can contain other objects in order, for example, a list. Integers cannot contain other objects; they single whole numbers. Trying to do an operation unsuitable for a specific type will raise a TypeError.

In this tutorial, we will detail the TypeError: ‘int’ object is not subscriptable error with examples to show you how to solve the problem in your code.


Table of contents

  • What is TypeError
  • TypeError: ‘int’ object is not subscriptable
    • Trying to Access the Index of an Integer Object
    • Solution
  • Summary

What is TypeError

TypeError occurs when you try to operate on a value that does not support that operation.

This particular TypeError occurs when we try to do an operation supported by subscriptable objects like strings, lists, tuples, and dictionaries, on an integer, which is not a subscriptable object. Subscriptable objects implement the __getitem__() method, whereas integers do not implement the __getitem__() method.

Like integers, floating-point numbers are not subscriptable objects. If we try to index or slice a floating-point number like a list, for example, to get the first digit, we will raise the error “TypeError: ‘float’ object is not subscriptable“.

Another example of a TypeError is concentrating a string with an integer using the ‘+’ operator. We go into more detail on this TypeError in the article titled “Python TypeError: can only concatenate str (not “int”) to str Solution“.

Methods also do not implement the __getitem__() method, and cannot be accessed like a list with square brackets. If you try to access a method like a list you will raise the error “TypeError: ‘method’ object is not subscriptable“.

Let’s look at an example of accessing an item in a list using indexing, remembering that the index of an array starts with 0:

# Define fruit basket list

fruit_basket = ["apple", "orange", "pineapple"]

#print output

print(fruit_basket[2])
pineapple

The code returns pineapple, showing us that lists contain objects, and we can retrieve them using indexing. We cannot apply this indexing operation to a non-subscriptable value like an integer or a float.

TypeError: ‘int’ object is not subscriptable

Trying to Access the Index of an Integer Object

In this example, we’ll start by creating an integer object and try to perform indexing on it.

# an integer

number = 40

# print the 0th index of an integer

print(number[0])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(number[0])

TypeError: 'int' object is not subscriptable

The TypeError tells us that performing indexing or other subscriptable operations on an integer value is illegal in Python.

Moving from the simple case, the most common scenario where we encounter this error is when our program requests input from a user, converts the information into an integer and later tries to access the input data as a string type value.

Let’s look at an example of a program requesting a sort code and account number. The program uses slicing to separate the two values from the input and prints the two values.

# Sort code and Account number input

bank_details = int(input("Enter your sort code and account number: "))

# Get sort code using slicing

sort_code = bank_details[0:5]

# Get account number using slicing

account_number = [5:]

#print two separate values

print('Sort Code: ', sort_code)

print('Account number: ', account_number)
Enter your sort code and account number: 00000012345678

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 sort_code=bank_details[0:5]

TypeError: 'int' object is not subscriptable

The traceback informs us that the statement sort_code = bank_details[0:5] is the cause of the TypeError. We are trying to get the sort code using the illegal subscriptable operator [0:5] on the bank_details integer value.

Solution

To solve this problem, we need to remove the int() function from the input() method, which will give us the bank_details as a string object, which is subscriptable.

# Sort code and Account number input

bank_details = input("Enter your sort code and account number: ")

# Get sort code using slicing

sort_code=bank_details[0:6]

# Get account number using slicing

account_number=bank_details[6:]

# Print output

print('Sort code: ', sort_code)

print('Account number:  ', account_number)
Enter your sort code and account number: 00000012345678

Sort code:  000000

Account number:   12345678

We can successfully index the bank_details string and obtain the sort code and account number. To learn more about getting substrings from string objects, visit the article titled “How to Get a Substring From a String in Python“.

Summary

Congratulations on making it to the end of the tutorial. To summarize, we raise the TypeError: ‘int’ object is not subscriptable when trying to perform illegal subscriptable operations on an integer. We can only perform subscriptable operations on subscriptable objects, like a list or a dictionary.

When performing slicing or indexing, ensure the value you are trying to slice is not an integer value. If you do not need to perform a subscriptable operation, you can remove the indexing on the integer. In program design, ensure you use sensible and meaningful names for your variables. The variable names should describe the data they hold, which will reduce the likelihood of TypeErrors.

To learn more about Python specifically for data science and machine learning, go to the online courses page on Python.

Have fun and happy researching!

‘int’ object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

list1 = [1, 2, 3]
print(list1[0][0])

If we run the code, you will receive the same TypeError in Python3.

TypeError: 'int' object is not subscriptable

Here the index of the list is out of range. If the code was modified to:

print(list1[0])

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

1

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

int([x[age1]])

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Hence, it’s better to code this way:

name = input("What's your name? ")
age = int(input('How old are you? '))
twenty_one = 21 - age
if(twenty_one < 0):
    print('Hi {0}, you are above 21 years' .format(name))
elif(twenty_one == 0):
    print('Hi {0}, you are 21 years old' .format(name))
else:
    print('Hi {0}, you will be 21 years in {1} year(s)' .format(name, twenty_one))

The output:

What's your name? Steve
How old are you? 21
Hi Steve, you are 21 years old

Понравилась статья? Поделить с друзьями:
  • Ошибка typeerror expected string or bytes like object
  • Ошибка typeerror dict object is not callable
  • Ошибка type pressure check tyres
  • Ошибка type mismatch в excel это
  • Ошибка twain сканера windows 10