Python for Loop: In this article, you’ll learn to iterate over a sequence of elements using the different variations of for loop.
What is for loop in Python?
The for loop in Python is used to repeat over a sequence (list, tuple, string) or other iterable objects. Repeating over a sequence is called traversal.
Syntax of for Loop
for val in sequence: Body of for
Here, Val is the variable that takes the estimation of the thing inside the sequence on every emphasis.
Loop proceeds until we arrive at the last thing in the arrangement. The collection of for circle is isolated from the remainder of the code using indentation.
Flowchart of for Loop
Example: Python for Loop
# Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum)
When you run the program, the output will be:
The sum is 48
The range() function
We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
We can also characterize the beginning, stop, and step size as the range(start, stop,step_size). step_size defaults to 1 if not provided.
The range object is “lazy” it might be said in light of the fact that it doesn’t produce each number that it “contains” when we make it. In any case, it’s anything but an iterator since it bolsters in, len, and __getitem__ operations.
This function doesn’t store all the values in memory; it would be wasteful. So it recollects the beginning, stop, step size, and generates the next number on the go.
To force this function to output all the items, we can use the function list().
The following example will clarify this.
print(range(10)) print(list(range(10))) print(list(range(2, 8))) print(list(range(2, 20, 3)))
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing genre = ['worldofitech', 'python programming', 'this article'] # iterate over the list using index for i in range(len(genre)): print("I like", genre[i])
I like worldofitech I like python programming I like this article
Please feel free to give your comment if you face any difficulty here.
For More Latest Articles Click on Below Link