TypeError: 'int' object is not subscriptable

Asked 2 years ago, Updated 2 years ago, 14 views

I'm solving an internal problem, but there's an error called TypeError: 'int' object is not writable, what is this error?

def solution(a, b):
    c = 0
    for i in range(len(a)):
        a = a[i] + b[i]
        c = c + a
    return answer

a = [1,2,3,4]
b = [-3,-1,0,2]
solution(a, b)

python

2022-09-20 17:45

2 Answers

Len(a) is required, which is a problem caused by specifying a as an int object rather than a list in the for statement.

It will be solved by modifying it as follows.

def solution(a, b):
    c = 0
    for i in range(len(a)):
        d = a[i] + b[i]
        e = c + d
    return answer

a = [1, 2, 3, 4]
b = [-3, -1, 0, 2]
f = solution(a, b)
print(f)


2022-09-20 17:45

Look at the error message, interpret it, and reproduce it.

>>> 1[1]
<stdin>:1: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
>>> a = 3
>>> a[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

Occurs when you attempt to index an integer object. I mean, there's this code that you run, and if you look it up,

a[i] + b[i]

There's only this part, and a or b is int

But obviously, when we passed it to the function, a, b was the list, but if we think about what's wrong, we can see that a = a[i] + b[i] is an int.


2022-09-20 17:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.