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.
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | all |
📝 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
🏷️ Related Keywords / Statements
💡 Related Cases
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.