In Python, a for-loop iterates over the members of a sequence (that is either a list, a tuple, a dictionary, a set, or a string) using an iterating variable which keeps track of the current item in the sequence. This allows a piece of code to be executed repeatedly for each member of the sequence.
The
for
-loop does not require an indexing variable to be set beforehand.
This code will find the sum of all the numbers stored in a list using a for
-loop in Python.
# List of numbersnumbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]# variable to store the sumsum = 0# iterate over the listfor val in numbers:sum = sum+val# Output: The sum is 48print("The sum is", sum)
The loop in the above code will run nine times as it iterates over the list and adds each item to the previously calculated sum for each iteration.
Free Resources