Home python Error “int 'object is not subscriptable” when trying to access an element...

Error “int ‘object is not subscriptable” when trying to access an element of a tuple





Traceback (most recent call last):
File "min_way_to_achieve_the_number.py", line 20, in & lt; module & gt;
while (ways [ind] [0]! = finish_num):
TypeError: 'int' object is not subscriptable

Answer 1, authority 100%

What is the meaning and reason of the error

The error “‘X’ object is not subscriptable” means that you are trying to reference an object of type X by index, but that type does not support reference by index. For example, 1 [0] doesn’t make sense.

After the first iteration of the loop, ways contains the value [(2, 0), 5, 1, 4, 1, 0, 1] . It is noticeable that not tuples were added, but simply numbers. The code accesses these numbers by index, which leads to our error.

Why aren’t tuples being added? It’s about the signature of the extend method:

extend (self, iterable):

This method takes a iterable , iterates over and adds each value to the list. In your example, it gets a tuple of two numbers and adds those numbers to the list.

How to add a tuple to a list with one element

The simplest would be to use the append method, which takes 1 object.

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

It is also possible to create a new tuple or list from a single element, as recommended in the adjacent answer.

# single element tuple: (a,)
# comma is required!
ways.extend (((first_op (ways [ind] [0], ind + 1),))
# a list of one element: [a]
ways.extend ([(first_op (ways [ind] [0], ind + 1)])

Answer 2, authority 33%

This is how it works:

def first_op (x):
  return x + 3
def second_op (x):
  return x * 2
def third_op (x):
  return x - 2
ind = 0
finish_num = 100
ways = [(2, 0)]
while (ways [ind] [0]! = finish_num):
  ways.extend ([(first_op (ways [ind] [0]), ind + 1)])
  ways.extend ([(second_op (ways [ind] [0]), ind + 1)])
  ways.extend ([(third_op (ways [ind] [0]), ind + 1)])
  ind + = 1
print (ways)

The point was that you were expanding the list not with tuples but with scalars.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions