4.2. for 문법
for
Statements
The for
statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
파이썬의 for
문법은 C또는 파스칼에서 사용하는 것과 약간 다르다. 파스칼에서처럼 산술연산을 반복하거나, C에서처럼 반복 단계 및 정지 상태를 정의하는 권한을 사용자에게 주는 대신, 파이썬의 for
문법은 모든 시퀀스(리스트 또는 문자열)의 값들을 시퀀스 안의 순서대로 반복 사용한다.
>>> # 몇 가지 문자열을 측정해보자.
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
만약 반복되는 문법 안에서 시퀀스(내용)를 수정하고 싶다면(예를 들어, 어떤 값을 복사하고 싶다면) 가장 먼저 해야 할 일은 복사본을 만드는 일이다. 시퀀스 전체의 반복(iterating)은 복사본을 만들지 않기 때문이다. 슬라이스 기능을 이용하면 이 작업을 편리하게 할 수 있다.
>>> for w in words[:]: # Loop (반복문법)을 슬라이스로 복사된 전체 리스트에 적용한다.
# 우리는 앞에서 변수[:]가 그 변수에 대한 리스트 복사본임을 본 적이 있다.
#변수 words는 앞선 예시에서 설정된 값을 계속 사용하고 있다.
... if len(w) > 6:
... words.insert(0, w)
# .insert 는 지정된 인덱스의 자리에 주어진 값을 집어넣는다.
# 총 글자 수가 6보다 큰 'len(w) > 6'
# defenestrate를 0번 자리에 집어넣었다.
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']