Python 101Free
CONTROL FLOW

Loops

Doing things repeatedly with for and while.

SECTION 01

for over an iterable

Python's for loop is not a counter loop. It walks over an iterable, binding each item to the loop variable in turn. The iterable can be a list, a string, a dict, a file object, a range, or any object that defines an iterator.

range(start, stop, step) is the closest thing to the C-style counter. It produces an iterator that yields integers in the requested range. For most purposes you write for i in range(n): and read it as "do this n times".

If you find yourself reaching for an index just to read both the index and the value, use enumerate(items). It yields (i, item) pairs and is more idiomatic than tracking an integer manually.

python
for i in range(3):
    print(i)             # 0, 1, 2

for i, name in enumerate(["a", "b"]):
    print(i, name)       # 0 a, then 1 b
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in