for Iterate over sequence

Last updated: 2026-09-22

for Iterate over sequence

for iterates over an iterable; an attached else runs only if the loop wasn't broken.

CategoryKeywords & Statements
KindKeyword / Statement
Python Versionall

📝 Syntax

for var in iterable:
    block
[else:
    block]

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

0 1 2
More case studies coming soon — check back later.

❓ FAQ

QWhen iterating over a dictionary, what do you get?
ABy default you get the keys. Use `d.values()` for the values, and `d.items()` to get both keys and values, e.g. `for k, v in d.items():`.
QCan you modify a list while iterating over it?
ANot recommended. Adding or removing elements while iterating skips or misses items. Common approaches are to iterate over a copy (`for x in lst[:]`) or build a new list with a list comprehension.
QWhy does Python's `for` not have the C-style `i++` form?
ABecause Python's `for` iterates over an iterator rather than counting. You get counting directly with `for i in range(n)`, producing 0 to n-1. The loop ends when the iterator is exhausted, not when a condition expression becomes false.
QWhen does the `else` after a `for` run?
AIt runs only when the loop body finishes all iterations without executing `break`. For example, when searching a list for an element, if it is not found the `else` supplies a fallback.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏