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

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

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

Автор оригинала: Team Python Pool.

Вступление

Некоторые объекты в python являются подписными. Это означает, что они удерживают и удерживают другие объекты, но целое число не является объектом с подпиской. Мы используем целые числа, используемые для хранения целых числовых значений в python. Если мы рассматриваем целое число как объект с возможностью подписки, оно вызовет ошибку. Итак, мы будем обсуждать конкретный тип ошибки, которую мы получаем при написании кода на python, то есть TypeError: объект ‘int’ не является подписываемым. Мы также обсудим различные методы преодоления этой ошибки.

Что такое TypeError: объект ‘int’ не поддается подписке?

Что такое TypeError?

Ошибка TypeError возникает при попытке оперировать значением, которое не поддерживает эту операцию. Давайте разберемся с помощью примера:

Предположим, мы попытаемся объединить строку и целое число с помощью оператора ‘+’. Здесь мы увидим TypeError, поскольку операция + не разрешена между двумя объектами разных типов.

#example of typeError

print(S + number)

Выход:

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

Объяснение:

Здесь мы взяли строку “Литеральные решения” и взяли число. После этого в операторе печати мы попытаемся добавить их. В результате: произошла ошибка типа.

Что такое объект ‘int’, не поддающийся подписке?

Когда мы пытаемся объединить строковые и целочисленные значения, это сообщение говорит нам, что мы рассматриваем целое число как подписываемый объект. Целое число не является подписываемым объектом. Объекты, содержащие другие объекты или типы данных, такие как строки, списки, кортежи и словари, могут быть подписаны. Давайте возьмем пример:

1. Number: typeerror: Объект ‘int’ не поддается подписке

#example of integer which shows a Typeerror

print(number[0])

выход:

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

Объяснение:

Здесь мы взяли число и попытались напечатать сквозное индексирование, но оно показывает typeerror, так как целые числа не поддаются подписке.

2. List: typeerror: объект ‘int’ не является подписываемым

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

#list example which will run correctly

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

Выход:

Объяснение:

Здесь, во-первых, мы взяли список имен и получили к нему доступ с помощью индексации. Таким образом, он показывает результат в виде решений.

Повседневный Пример Того, Как может Произойти typeerror: ‘int’ объект не является подписываемым

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

#Our program begins from here
(input("what is your birth date?"))
[0:2]
[2:4]
[4:8]

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

Выход:

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

Объяснение:

Здесь, во-первых, мы взяли программу для печати даты рождения отдельно с помощью индексации. Во-вторых, мы взяли целочисленные входные данные даты рождения в виде даты, месяца и года. В-третьих, мы разделили дату, месяц и год с помощью индексации, а после этого печатаем их отдельно, но получаем вывод ad TypeError: объект ‘int’ не поддается подписке. Как мы изучали выше, объект integer не является подписываемым.

Решение TypeError: объект ‘int’ не является подписываемым

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

Чтобы решить эту проблему сейчас, мы удалим оператор int() из нашего кода и запустим тот же код.

#remove int() from the input()
("what is your birth date?")
[0:2]
[2:4]
[4:8]

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

Выход:

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

Объяснение:

Здесь мы только что взяли входные данные в строку, просто удалив int(), и теперь мы можем сделать индексацию и href=”https://docs.python.org/2.3/whatsnew/section-slices.html”>нарезать в нем легко, так как он стал списком, который можно подписывать, так что никакой ошибки не возникает. href=”https://docs.python.org/2.3/whatsnew/section-slices.html”>нарезать в нем легко, так как он стал списком, который можно подписывать, так что никакой ошибки не возникает.

Должен Читать

    [Решено] TypeError: Только Массивы Размера 1 Могут Быть Преобразованы В Скаляры Python Error 50+ Часто Задаваемых Вопросов Python Для Интервью Python Max Int | Каково максимальное значение типа данных int в Python Python int to Binary | Integer to Binary Преобразование Недопустимый литерал для int() с базой 10 | Ошибка и разрешение

Вывод: Typeerror: объект ‘int’ не поддается подписке

Мы узнали все ключевые моменты о TypeError: объект ‘int’ не поддается подписке. Существуют такие объекты, как список, кортеж, строки и словари, которые могут быть подписаны. Эта ошибка возникает при попытке выполнить индексацию или нарезку целого числа.

Предположим, нам нужно выполнить такие операции, как индексация и нарезка целых чисел. Во-первых, мы должны преобразовать целое число в строку, список, кортеж или словарь.

Теперь вы можете легко решить этот python TypeError, как smartcode.

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

Счастливого Пифонирования!

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!

Table of Contents
Hide
  1. What is Subscriptable in Python?
  2. How do you make an object Subscriptable?
  3. How to Fix TypeError: ‘int’ object is not subscriptable?
    1. Solution
  4. Conclusion

In Python, we use Integers to store the whole numbers, and it is not a subscriptable object. If you treat an integer like a subscriptable object, the Python interpreter will raise TypeError: ‘int’ object is not subscriptable.

In this tutorial, we will learn what ‘int’ object is is not subscriptable error means and how to resolve this TypeError in your program with examples.

Subscriptable” means that you’re trying to access an element of the object. The elements are usually accessed using indexing since it is the same as a mathematical notation that uses actual subscripts.

How do you make an object Subscriptable?

In Python, any objects that implement the __getitem__ method in the class definition are called subscriptable objects, and by using the  __getitem__  method, we can access the elements of the object.

For example, strings, lists, dictionaries, tuples are all subscriptable objects. We can retrieve the items from these objects using indexing.

Note: Python doesn't allow to subscript the NoneType if you do Python will raise TypeError: 'NoneType' object is not subscriptable

How to Fix TypeError: ‘int’ object is not subscriptable?

Let us take a small example to read the birth date from the user and slice the day, months and year values into separate lines.

birth_date = int(input("Please enter your birthdate in the format of (mmddyyyy) "))

birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]

print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)

If you look at the above program, we are reading the user birth date as an input parameter in the mmddyy format.

Then to retrieve the values of the day, month and year from the user input, we use slicing and store it into a variable.

When we run the code, Python will raise a TypeError: ‘int’ object is not subscriptable.

Please enter your birthdate in the format of (mmddyyyy) 01302004
Traceback (most recent call last):
  File "C:PersonalIJSCodemain.py", line 3, in <module>
    birth_month = birth_date[0:2]
TypeError: 'int' object is not subscriptable

Solution

 In our example, we are reading the birth date as input from the user and the value is converted to an integer. 

The integer values cannot be accessed using slicing or indexing, and if we do that, we get the TypeError. 

To solve this issue, we can remove the int() conversion while reading the input from the string. So now the birth_date will be of type string, and we can use slicing or indexing on the string variable.

Let’s correct our example and run the code.

birth_date = input("Please enter your birthdate in the format of (mmddyyyy) ")

birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]

print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)

Output

Please enter your birthdate in the format of (mmddyyyy) 01302004
Birth Month: 01
Birth Day: 30
Birth Year: 2004

The code runs successfully since the int() conversion is removed from the code, and slicing works perfectly on the string object to extract a day, month and year.

Conclusion

The TypeError: ‘int’ object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects.

The issue can be resolved by removing any indexing or slicing to access the values of the integer object. If you still need to perform indexing or slicing on integer objects, you need to first convert that into strings or lists and then perform this operation.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Int 69 tml diagnose ошибки
  • Insurgency ошибка this game requires steam
  • Insurgency ошибка battleye
  • Insurgency sandstorm ошибка при запуске

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии