📒 Today I Learn/👾 Error

[Python] IndexError: list index out of range

ny:D 2024. 5. 7. 11:00

240507 Today I Learn

👾 IndexError: list index out of range
인덱스 에러 : 리스트 인덱스가 범위를 벗어남

 

문제 상황

def solution(cards1, cards2, goal):
    for i in goal:
        if i == cards1[0]:
            cards1.pop(0)
        elif i == cards2[0]:
            cards2.pop(0)
        else:
            return 'No'
    return 'Yes'

 

▶︎ 오류 test case

cards1 cards2 goal result
["i", "water", "drink"] ["want", "to"] ["i", "want", "to", "drink", "water"] "No"

 

에러 탐색

수기로 루프를 돌아보자.

  • for 0 in goal:
    • i == cards1[0] : `True`, cards1.pop(0)
      → cards1 = [ 'drink', 'water']
  • for 1 in goal:
    • i == cards2[0] : `True`, cards2.pop(0)
      → cards2 = ['to']
  • for 2 in goal:
    • i == cards2[0] : `True`, cards2.pop(0)
      → cards2 = [] 
  • for 3 in goal:
    • i == cards1[0] : `False`
    • i == cards2[0] : list index error

 

cards2는 빈 리스트이므로,
빈 리스트에서 index가 0인 값을 슬라이싱 하려고 하면 오류가 나는 것이다!

문제 해결

`cards1`과 `cards2`가 빈 리스트가 아닌 경우에서 조건 1과 조건2를 적용해주면 된다.

def solution(cards1, cards2, goal):
    for i in goal:
        if len(cards1) != 0 and i == cards1[0]:
            cards1.pop(0)
        elif len(cards2) != 0 and i == cards2[0]:
            cards2.pop(0)
        else:
            return 'No'
    return 'Yes'