Python/Python Programming

[Python] for문에 리스트 순회시 remove가 정상적으로 반영되지 않는 이유

Pydole 2020. 5. 18. 10:56

 

 

리스트 원본 자체를 loop에서 remove 정상적으로 반영되지 않기 때문에, 스텝 슬라이싱을 이용하면 된다.

 

# lst 원본 자체를 for문


lst = [ i for i in range(10) ]

for i in lst:
    lst.remove(i)

lst



[1, 3, 5, 7, 9]          # 원하는 결과가 나오지 않았다.

 

스텝 슬라이싱으로 for문



lst = [ i for i in range(10) ]

for i in lst[::]:
    lst.remove(i)

lst


[]

 

docs.python.org/3/tutorial/controlflow.html#for-statements