Search code examples
pythontypeerror

Why is the code showing 'int' object is not subscriptable?


x = int(input())
l =[]


for i in range(x):
  l.append(input().split(" "))

for i in range(x):
  
  k = int(l[i][1])
  sum = int(l[i][2])
  odd =[]
  for j in range(int(l[i][0])):
        
    odd.append(1+2*j)
    

  for j in range(len(odd)):
      
    s =0
    for l in range(len(odd)):
      if(odd[j]==odd[l]):
        s = s+ odd[l]*k
      else:
        s = s+ odd[l]
    if(s==sum):
      print(odd[j])
      break

When I run this code, it works perfectly fine for 1 iteration. But as soon as we move to next iteration, the code starts showing error:

TypeError: 'int' object is not subscriptable

in the line where I have declared k = l[i][1]. What's causing this error and how can I solve it?


Solution

  • The line

    for l in range(len(odd)):
    

    assigns an int to l. Loops (and all other control structures for that matter) don't introduce a new scope in Python, so that l is the exact same variable as the l you defined at the start. When k = l[i][1] is reached on the next iteration, you're attempting to index an int, hence the error.

    You'll need to pick a different name for the variable in the for loop.