본문 바로가기
파이썬

파이썬 (Python) 목록 색인이 범위를 벗어남-반복

by º기록 2020. 12. 26.
반응형
for i in range(len(lst)):    
   if lst[i][0]==1 or lst[i][1]==1:
        lst.remove(lst[i])
return lst

그러면 "IndexError : list index out of range"가 표시됩니다. 왜 이런 일이 발생합니까?

 

해결 방법

 

반복하는 목록을 수정하고 있습니다. 그렇게하면 목록의 크기가 줄어들 기 때문에 결국 lst [i] 는 목록의 경계를 넘어 가게됩니다.

>>> lst = [1,2,3]
>>> lst[2]
3
>>> lst.remove(1)
>>> lst[1]
3
>>> lst[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

새 목록을 만드는 것이 더 안전합니다.

return [item for item in lst if item[0]!=1 and item[1]!=1]

 

참조 페이지 https://stackoverflow.com/questions/20819504

 

 

반응형

댓글