C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: If you need to get adjacent characters, or test many indexes at once, the for-loop that uses range() is best.
Python program that uses for-loop on strings
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])
Output
a Loop 1
b
c
a Loop 2
b
c
Note: It is possible to create a new collection, as with range(), immediately for the for-loop to act upon.
RangeAnd: This makes the for-loop more similar to the syntax forms in other languages.
Python program that shows for-loop
names = ["Sarah", "Rakesh", "Markus", "Eli"]
# Loop over list.
for name in names:
print(name)
Output
Sarah
Rakesh
Markus
Eli
Index: Enumerate here returns an index of 0 for "boat." This makes sense as the value "boat" is the first element in the list.
Python program that uses enumerate, list
list = ["boat", "car", "plane"]
# Call enumerate to loop over indexes and values.
for i, v in enumerate(list):
print(i, v)
Output
0 boat
1 car
2 plane
Python program that uses reversed
# Use reversed on a range.
for i in reversed(range(0, 3)):
# Display the index.
print(i)
Output
2
1
0
Python program that uses for-loop, one-line
# Use single-line for-loop syntax.
for number in range(0, 10, 2): print(number)
Output
0
2
4
6
8