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.
Here is a program that loops over a string
. The value "abc" has 3 letters in it—3 characters. We use the for
-keyword.
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.
range()
, immediately for the for
-loop to act upon.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
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.
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
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
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.