TypeError: 'int' object is not subscriptable
조회수 8406회
내적 문제를 푸는중인데요, TypeError: 'int' object is not subscriptable 이라는 에러가 뜨는데, 이건 뭐하는 에러인가요?
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)
2 답변
-
len(a)를 해야 하는데, for문에서 a를 리스트가 아닌 int 객체로 지정하면서 생기는 문제입니다.
다음과 같이 수정하면 해결될 겁니다.
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)
-
에러메시지를 보고 해석해 보고, 그걸 재현해 보세요.
>>> 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
정수객체에 대해 인덱싱을 하려고 하면 발생합니다. 실행하는 코드 중에 이런 게 있다는 말이고, 그걸 찾아보면,
a[i] + b[i]
이 부분 밖에 없고, a나 b 가 int 라는 말이고,
그런데, 분명히 함수에 전달할 때에는 a, b 가 리스트였는데 뭐가 문젠가 생각을 해 보면, a = a[i] + b[i] 실행하면서 a 가 int 가 된다는 걸 알 수 있죠.
댓글 입력