새소식

Python

Python 알고리즘 - 리스트 제곱 시키기에서 IndexError: list index out of range 오류 해결하기 with ChatGPT

  • -

주피터 노트북 환경에서 리스트의 각 요소를 제곱한 리스트를 반환하는 함수를 작성하다 다음과 같은 오류를 발견했다. 

 

오류

IndexError: list index out of range > 범인은 new_list=list[i]**2 여기 있다던데..

#내 함수 코드

def square_numbers(list):
    new_list=[]
    for i in list:
        new_list=list[i]**2
    return new_list
 
 #이 코드를 실행했을 때 오류가 남
 square_numbers([1,2,3,4,5])

 

도와조 챗지피티

The error you are seeing, IndexError: list index out of range, occurs when you try to access an element of a list with an index that is out of the range of the list. In your code, the issue is with the line new_list=list[i]**2.
When you use a for loop like for i in list, i takes on the value of each element in the list list, not the index of that element. So when you try to access list[i] with i as an element, you are actually trying to access an element of list with a value that may be out of range.

목록에서 for i와 같은 for 루프를 사용할 때 i는 해당 요소의 인덱스가 아니라 목록 목록의 각 요소 값을 취합니다. 따라서 i를 요소로 사용하여 list[i]에 액세스하려고 하면 실제로 범위를 벗어날 수 있는 값으로 목록의 요소에 액세스하려고 하는 것입니다.

To fix this error, you should replace new_list=list[i]**2 with new_list.append(i**2). This will append the square of each element to new_list without trying to access an out-of-range element of list.

 

해결 코드

def square_numbers(lst):
    new_list = []
    for i in lst:
        new_list.append(i**2)
    return new_list

 

결론

i는 변수이지, 인덱스명이 될 수 없기에 index error가 발생한 것이다. (i라서 1씩 커지는 정수로 생각해 당연히 인덱스명이 될 수 있을 거라 생각한 내가 바부) 리스트 안의 요소를 하나하나 **2 제곱시키고, 그 값을 new_list에 append 더한다. 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.