코딩하는 몽구리

[Python] TypeError: 'NoneType' object is not subscriptable 본문

Python

[Python] TypeError: 'NoneType' object is not subscriptable

코딩구리 2023. 1. 8. 14:06

안녕하세요!

코딩덕입니다:)

오늘은 파이썬에서 

TypeError: 'NoneType' object is not subscriptable

에러에 대해서 알아보도록 하겠습니다.

 

이 에러 같은 경우에는 NoneType인 변수에서

특정 index에 접근하려고 할때 발생하는 에러입니다. 

에러가 발생한 경우를 통해서 알아보도록 할게요!


0. 입력값 예시

 

 

문제 원인 코드 1

import sys
sys.stdin=open("input.txt", "rt")

T=int(input())
for t in range(T):
    n, s, e, k = map(int, input().split())
    a=list(map(int, input().split()))
    a=a[s-1:e].sort()
    print("#%d %d"%(t+1,a[k-1]))

 

 

 

위 코드에서 NoneType 에러가 발생하는 이유는 

sort()함수 때문입니다. 

sort()함수 같은 경우에는 return값이 None이기 때문에 

a=a[s-1:e].sort()코드는 a변수에 None을 담게 됩니다.

실제로 a를 출력하게 되면 None이 담기는 것을 

확인할 수 있습니다. 

a변수 출력 값

 

그래서 a[k-1]에 접근하게 되면 NoneType에서

index값에 접근하려고 하니 에러가 발생하는 것입니다. 

 

위 에러를 해결해주기 위해서는

sort()함수의 위치를 변경시켜주면 됩니다. 

a=a[s-1:e]

a.sort()

나눠서 코드를 작성하게 되면 a변수에 

None이 담기지 않기 때문에 정상적으로

코드가 작동하게 됩니다. 

 

에러 해결 코드

import sys
sys.stdin=open("input.txt", "rt")

T=int(input())
for t in range(T):
    n, s, e, k = map(int, input().split())
    a=list(map(int, input().split()))
    a=a[s-1:e]
    a.sort()
    print("#%d %d"%(t+1,a[k-1]))

 

'Python' 카테고리의 다른 글

[5일차] 비밀번호 생성기 만들기  (1) 2023.05.30
[Numpy] ndarray의 데이터 타입  (0) 2023.04.17
함수  (0) 2022.12.21
variable & List (boostcamp)  (0) 2022.12.11
1부터 n까지 정수의 합 구하기  (0) 2022.07.30