For. In Python we find lists, strings, ranges of numbers. We often want to loop over (iterate through) these values—with the for-loop this is possible.
We often loop over characters—we can directly loop over a string with a for-loop. And we can use a for-loop with the range method to loop over indexes.
An example. Here is a program that loops over a string. The value "abc" has 3 letters in it—3 characters. We use the for-keyword.
Tip If you need to get adjacent characters, or test many indexes at once, the for-loop that uses range() is best.
s = "abc"# Loop over string.
for c in s:
print(c)
# Loop over string indexes.
for i in range(0, len(s)):
print(s[i])a Loop 1
b
c
a Loop 2
b
c
List. A for-loop acts upon a collection of elements, not a min and max. In for, we declare a new variable. And after the in-keyword, we specify the collection we want to loop over.
And This makes the for-loop more similar to the syntax forms in other languages.
names = ["Sarah", "Alice", "Mark", "Bill"]
# Loop over list.
for name in names:
print(name)Sarah
Alice
Mark
Bill
Enumerate. This receives an iterable. It returns each index and the associated value with each index. The result is an object, which has two parts (index, value). Here we use it on a list.
Detail Enumerate here returns an index of 0 for "boat." This makes sense as the value "boat" is the first element in the list.
list = ["boat", "car", "plane"]
# Call enumerate to loop over indexes and values.
for i, v in enumerate(list):
print(i, v)0 boat
1 car
2 plane
Reverse. We can loop over any sequence in reverse. We use the reversed() method. This returns a view of the sequence in inverted order. It does not change the original sequence.
# Use reversed on a range.
for i in reversed(range(0, 3)):
# Display the index.
print(i)2
1
0
One-line syntax. Typically a loop uses 2 or more lines, but we can place the entire loop on a single line if needed. This can make short loops easier to read (and files easier to edit).
# Use single-line for-loop syntax.
for number in range(0, 10, 2): print(number)0
2
4
6
8
Iter. We can use the iter built-in to create custom for-loop logic. The iter method (and next) can be used to iterate over a collection in a special way.
With the for-loop we can loop over collections like lists. But we can also loop over the characters in a string. This keyword is versatile in the types it handles.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.