Python – “bool is not subscriptable” error when not indexed to bool – Python

“bool is not subscriptable” error when not indexed to bool – Python… here is a solution to the problem.

“bool is not subscriptable” error when not indexed to bool – Python

I have the following features:

    def in_loop(i):
        global loop_started
        if i == '[':
            loop_started = True
            return [True, 'loop starting']
        if loop_started:
            if i == ']':
                loop_started = False
                return [True, 'loop over']
            return True
       return False

I

believe this returns a tuple and when I’m “]” it looks like (True, ‘loop over’).
Then I tried indexing it with

index

for index, i in enumerate(code):
    if in_loop(i):
        loop_counter += 1
        if in_loop(i)[1] == 'loop starting':
            loop_start = index
        if in_loop(i)[1] == 'loop over':
            loops[f'loop{loop_num}'] = {'start': loop_start, 'end': index}
            loop_num += 1

But this throws an error

TypeError: 'bool' object is not subscriptable

Also, Code = “+++++[-][-]].

Why do I get this error when I index tuples?

Solution

The problem is that when you reach characters like ‘+’ or ‘-‘, you’re actually returning a boolean value, but are accessing if in_loop(i)[1] == 'loop starting': nonetheless.

You must return a consistent return type for the second for loop code to work. For example, see the comments on your code below:

def in_loop(i):
    global loop_started
    if i == '[':
        loop_started = True
        return [True, 'loop starting']
    if loop_started:
        if i == ']':
            loop_started = False
            return [True, 'loop over']
        return True  #This will have side effects and is inconsistent with your other returns of in_loop
   return False  #This will have side effects and is inconsistent with your other returns of in_loop

Related Problems and Solutions