
Python 리스트 반복
Python 리스트의 모든 항목을 순회하는 방법은 여러 가지가 있다. for 루프로 직접 항목을 반복하거나, 인덱스 번호를 사용하거나, while 루프를 활용하거나, 리스트 컴프리헨션으로 간결하게 처리할 수 있다.
핵심 반복 방법 비교
반복 방법 | 문법 | 특징 | 사용 상황 |
---|---|---|---|
for 루프 | for item in list: | 항목에 직접 접근 | 값만 필요할 때 |
인덱스 기반 for | for i in range(len(list)): | 인덱스로 접근 | 인덱스가 필요할 때 |
while 루프 | while i < len(list): | 조건 기반 반복 | 복잡한 조건이 필요할 때 |
리스트 컴프리헨션 | [expr for item in list] | 간결한 한 줄 표현 | 새 리스트를 생성할 때 |
for 루프로 항목 반복
가장 일반적인 방법으로, 리스트의 각 항목을 직접 순회한다.
코드 블록
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
시각적 결과
apple
banana
cherry
인덱스 번호로 반복
range와 len 함수를 조합해 인덱스 번호를 사용하여 항목에 접근한다.
코드 블록
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
시각적 결과
apple
banana
cherry
while 루프로 반복
while 루프를 사용하여 인덱스를 수동으로 증가시키며 항목을 순회한다.
코드 블록
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
시각적 결과
apple
banana
cherry
리스트 컴프리헨션으로 반복
리스트 컴프리헨션은 짧은 구문으로 새로운 리스트를 생성하면서 반복 작업을 수행한다.
코드 블록
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
시각적 결과
apple
banana
cherry
조건부 반복
리스트를 반복하면서 특정 조건을 만족하는 항목만 처리할 수 있다.
for 루프와 조건문
코드 블록
thislist = ["apple", "banana", "cherry", "kiwi", "mango"]
for x in thislist:
if "a" in x:
print(x)
시각적 결과
apple
banana
mango
리스트 컴프리헨션과 조건문
코드 블록
thislist = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in thislist if "a" in x]
print(newlist)
시각적 결과
[’apple’, ‘banana’, ‘mango’]
💡 실용 팁:
• for 루프는 단순히 항목을 순회할 때 가장 읽기 쉽고 pythonic한 방법이다
• 인덱스가 필요하면 range(len())을 사용하거나 enumerate 함수를 고려한다
• while 루프는 복잡한 종료 조건이 필요할 때 유용하다
• 리스트 컴프리헨션은 새 리스트를 생성하면서 필터링하거나 변환할 때 간결하고 효율적이다
참고
W3C School - Python - Loop Lists