Iterating over a sequence is done with a for loop (that is either a list, a tuple, a dictionary, a set, or a string>
.
This is more like an iterator method seen in other object-oriented programming languages than the for keyword in other programming languages.
The for loop allows us to run a sequence of statements once for each item in a list, tuple, set, or other data structure.
Example
In a fruit list, print each fruit:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x>
Output:
Try it here
There is no need to set an indexing variable before using the for loop.
Creating a Loop in a String
Even though strings are iterable objects, they are made up of a series of characters:
Example
Follow the letters of the word "grapes" in a loop:
for x in "Grapes":
print(x>
Output:
Try it here
The break Statement
We can break the loop before it loops over all of the objects by using the break statement:
Example python simple programs
When x is "orange," exit the loop:
fruits = ["orange", "mango", "cherry"]
for x in fruits:
print(x>
if x == "mango":
break
Output:
Try it here