In this article, we would cover for loop in Python. We use loops to execute a particular instruction set repeatedly till a specific condition is met. Otherwise, we would have to write the instruction set for each relevant condition. This is definitely isn’t the preferred option. So, we have for loop.
The for loop in Python is a bit different from what we experience in other programming languages like C, Java etc. We generally provide the initial step, followed by the condition to which the initial step would respond and lastly the halting condition. Whereas, for loop in Python would iterate over the items in a sequence. The sequence here could be a list, tuple, etc.
The following is the syntax of for loop –
for VAR in SEQUENCE BODY
We discuss it with appropriate examples next.
for loop in Python
Example I. Here, we will see how to print each item in a list using for loop.
Let’s say we have list x,
x = ['book', 'science', 9, 'not available'] for ab in x: print(ab)
Note: We advise you to use proper spacing especially in the body of for loop. Otherwise, it may throw an IndentationError. We have used one tab space before print(ab)
The above code would return with the following –
book science 9 not available
Each item in the list x, would be taken up by variable ab sequentially. And, it prints the value stored in variable ab. Once all items in the list x are covered, the for loop exits on its own.
Example II. This example mainly deals with – how we can get the sum of all integer values stored in a list. Again, let’s say we have a list x,
x = [9,10,1] add = 0 for ab in x: add = add + ab print("Sum of all the values stored in list, x: ", add)
We declared a variable, add and assigned the initial value zero to it. The values stored in list x are stored in variable ab over each iteration. And, the it keeps adding to the add variable. The final outcome is stored in variable add.
In conclusion, we have discussed for loop in Python here. There are innumerable examples we can discuss but, it would be easy for us to manage if we understand the concept well.