Python のループは、インデックスカウンタを操作するのではなく、**iterable(コレクション)**を直接反復するように設計されており、きれいで読みやすくなっています。ループの 2 種類は for と while です。
for ループ — 項目を直接反復する
python
fruit [, , ]:
(fruit)
fruits = [, ]
i ((fruits)):
(fruits[i])
Python の for は要素そのものを反復するため、手動でインデックスを扱う必要がありません。これはインデックスベースのループより、きれいでエラーが起きにくくなっています。
# range — generate numbers
for i in range(5): # 0,1,2,3,4
for i in range(2, 10, 2): # 2,4,6,8 (start, stop, step)
# enumerate — when you DO need the index AND the item
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# zip — iterate multiple sequences in parallel
for name, age in zip(names, ages):
print(f"{name} is {age}")
# dict iteration
for key, value in user.items():
print(key, value)
enumerate(インデックス+項目)と zip(並行反復)は、不格好なインデックス操作を置き換えます。range(len(...)) の代わりにこれらを使いましょう。
while condition:
do_work()
if done: break # exit the loop
if skip: continue # jump to the next iteration
for item in items:
if item == target:
break
else:
# runs ONLY if the loop completed WITHOUT a break
print("not found")
ループの else は、ループが正常に終了した(break がなかった)場合に実行されます。探索パターンに便利です。
Python の反復モデル(インデックスではなく項目を直接ループする)は、読みやすくイディオム的なコードを書く上での中核です。
適切なツール(インデックスが必要なときは enumerate、並行反復には zip、回数には range、dict には .items())を知っていれば、他言語から来た初心者がよく書いてしまう range(len(...)) というアンチパターンを避けられます。
きれいな反復は Pythonic なコードの証であり、これらの補助ツールはほぼすべてのプログラムで使われます。