for statement는 loop를 위한 control structure의 대표격이다.
Python에서는 iterable 객체 (주로 collection type의 객체들)이
가지고 있는 item들을 iterate(순회)하는 용도로 사용된다.
프로그래밍을 배울 때, 구구단 출력과 같은 고전적인 예를 통해 배우고, 정말 기본 중의 기본으로 활용된다.
단, NumPy등을 익히게 되면서 loop가 아닌 matrix 를 이용한 처리 (쉽게 생각하면 많은 memory를 이용하여 반복을 덜하는 방식이라고 할 수 있음)가 보다 효율적이기 때문에 정말 필요한 경우 아니면 쓰지 말라고 애기를 하게 되지만...
2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator
[Python] Iterable and Iterator, plus Generator
Iterable and Iterator, and GeneratorIterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴.__iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반환
dsaint31.tistory.com
for statement는 정말 기본 중의 기본이다.
(반복을 얼마나 효율적으로 하느냐가 성능을 결정하기 때문에...)
기본 사용법

for loop_variable in iterable_obj:
for_block # loop body 또는 loop block으로 불림.
for statement의 사용법은 다음과 같음.
- keyword
for로 시작함. - 이후 loop variables가 놓인다. loop variables는 매 iteration에서 뒤에 놓인 iterable 객체의 item들이 할당됨.
- 이후 keyword
in이 놓임. (in이전이 loop variables이고 이후가iterable객체들이 놓임.) - 이후 iterate가 이루어질
iterable객체가 놓임 (복수 개를 사용시zip으로 묶어주면 됨.). - 이후
:가 놓임 (forstatement는 compound statement로:이후 다음 라인들은forstatement의 반복될 code block임.
code block은
forstatement가 시작하는 첫번째 line 보다 한단계 더 indentation 이루어짐.
이후 indent level이 감소하면 해당 code block이 종료함.
Compound Statement란?
Compound Statment란?Compound Statement is a statement that uses a colon :to sperate a header (head) from its body (=suite라고도 불림),which consists of eithera single simple statement on the same line oran indented code block of one or more statement
ds31x.tistory.com
list와 함께 사용하기
l = [0,1,2,3,4,5]
for c in l:
print(c)
print('\n')
- list
l의 item들이 순서대로 loop variablec에 할당되고, - loop block이 수행되고
- 이후 다시 loop variable
c에 다음 item이 할당되고 - 또 loop block이 수행되고
- 위 과정이
l의 마지막 item까지 반복됨.
결과는 다음과 같음.
0
1
2
3
4
5
str과 함께 사용하기.
string도 sequence type이기 때문에 다음과 같이 동작가능함.
s = 'abce1234ABC'
for c in s:
if c.isdigit():
print(c)
- 숫자에 해당하는 character
c만이 출력이 됨.
결과는 다음과 같음.
1
2
3
4
range 객체와 함께 사용하기 *
C에서처럼 시작과 끝 index에 해당하는 숫자를 이용하는 경우는 range 객체를 사용하는게 효율적이다.
range() 내장함수(built-in function)를 사용하여 range 객체를 생성함(개인적으로 생성자라고 보지만 내장함수라고 해도 틀린건 아님)
list나 tuple등은 자신의 모든 item들을 memory에 할당하는 객체이기 때문 매우 큰 수의 범위를 가지는 for statement에서 사용하기는 비효율적임.
for c in range(0,21,2):
print(c)
- ( [0,20] ) 에서 stepsize를 2로 취하기 때문에 짝수만이 출력됨.
결과는 다음과 같음.
0
2
4
6
8
10
12
14
16
18
20
복수개의 iterable 객체들을 한번에 반복하기
zip 함수로 여러 iterable 객체를 묶어주어 각 iteration에 복수의 loop variable을 사용할 수 있음.
단, zip으로 묶이는 각 iterable 객체의 item 갯수가 다른 경우 짧은 쪽에 의해 반복횟수가 결정됨.
다음의 예를 확인하라.
a = [0,1,2,3,4]
s = 'abcdefgh'
for i,c in zip(a,s):
print(f'{i},{c}')
- 5번의 반복만 이루어지는 것을 확인할 것.
- loop variable을 하나로 두면, 해당 variable은 tuple 객체가 된다.
결과는 다음과 같음.
0,a
1,b
2,c
3,d
4,e
code block인 loop block에는 다양한 statement가 놓일 수 있으며, 이는 중첩된 loop를 만들 수 있음.
(nested if statement에서와 비슷)
참고: break check - else
[Python] else: break checker
반복문에서 else는loop 가 break로 끝나지 않을 경우 수행되는 code block을 지정.조건문에서 else일반적으로 else의 경우, 앞서의 if 와 elif문들에서 실행된 block이 없는 경우 수행되는 것을 의미한다.2023.
ds31x.tistory.com
Reference
https://gist.github.com/dsaint31x/f28b8b3c59483abdb3119aa31ec44d01
py_for_Ex.ipynb
py_for_Ex.ipynb. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator
[Python] Iterable and Iterator, plus Generator
Iterable and Iterator, and GeneratorIterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴.__iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반환
dsaint31.tistory.com
[Python] while statement, break and continue:
Python의 경우, loop structure로 while statement와 for statement를 제공한다.Contol Flow와 Control Structure에 대한 개념은 다음 URL을 참고 :2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control F
ds31x.tistory.com
[Python] Control Structure and Control Flow
Control structure와 Control Flow란 무엇인가?2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control Flow 와 Control StructureAbstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은
ds31x.tistory.com
'Programming' 카테고리의 다른 글
| [ML] Ward’s linkage method (0) | 2023.08.06 |
|---|---|
| [matplotlib] bar chart 그리기 : error bar 포함 (0) | 2023.08.01 |
| [PyQt6] QSizePolicy 설정. (0) | 2023.07.03 |
| [Python] Regular Expression : re 요약 (0) | 2023.07.03 |
| [Python] str: Overloaded Operators (0) | 2023.07.02 |