파이썬(Python) 에러 IndexError 와 처리 방법
2월 09, 2023
In Python |
파이썬(Python) 에러 IndexError
원인과 처리 방법
파이썬의 IndexError는 시퀀스 범위를 벗어난 인덱스(예: 목록 또는 문자열)에 액세스하려고 할 때 발생합니다.
File: test.py
list = ['첫번째', '두번째', '세번째']
print(list[3])
결과
$ python test.py
File "/test.py", line 2, in <module>
print(list[3])
IndexError: list index out of range
list에 3개의 요소만 있기 때문에 인덱스 3이 유효하지 않아 IndexError가 발생했습니다.
처리 방법
시퀀스에 있는 인덱스에만 액세스해야 합니다.