Python For Loops
A for loop walks through the items of a sequence one at a time, running the same block of code for each item.
Looping over a sequence
Unlike a while loop, which repeats based on a condition, a for loop repeats once for every element in a collection. It works with any iterable, including lists, tuples, strings, and ranges of numbers. On each pass, a variable you name takes the value of the next item.
Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)A string is also a sequence, so a for loop can visit it character by character. This makes for loops handy for tasks such as counting letters or building new text.
Looping a set number of times with range
When you simply want to repeat something a fixed number of times, the built-in range function generates a sequence of numbers. range(stop) counts from 0 up to but not including stop, and you can also give it a start and a step.
Using range
# 0, 1, 2, 3, 4
for i in range(5):
print(i)
# 2, 4, 6, 8
for even in range(2, 10, 2):
print(even)Getting the index with enumerate
Often you need both the position and the value of each item. Rather than managing a separate counter, Python offers enumerate, which yields the index and the item together on each pass of the loop.
enumerate in action
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
# Start counting from 1 instead of 0
for position, color in enumerate(colors, start=1):
print(position, color)- range(stop): numbers from 0 up to stop - 1.
- range(start, stop): numbers from start up to stop - 1.
- range(start, stop, step): as above but jumping by step each time.
- enumerate(items): pairs of (index, item), with an optional start value.
- break and continue work in a for loop exactly as they do in a while loop.
Exercise: Python For Loops
What values does `range(5)` produce?