The for
loop in Python is used for iterating over a sequence (i.e. list, tuple, string, etc.) It executes a set of statements, once for each item in the sequence. The following is the syntax of the for
loop in Python:
main.py54 chars3 lines
Here, item
is a variable that takes on the value of each element in sequence
one by one, and the statements within the loop are executed for each value of item
.
Let's take an example of using a for
loop to iterate over a list of numbers and print them one by one:
main.py62 chars5 lines
Output:
main.py10 chars6 lines
As we can see, we have used the for
loop to iterate over the numbers
list and print each number in a separate line using the print()
function.
gistlibby LogSnag