Python for loop – A method to iterate sequence.
By using a for loop in Python, You can iterate a body/code block for a fixed number of times. The number of iterations depends on the size of the iterable object (such as range, list, tuple, dictionary, or string) passed in the loop.
In this tutorial, we will learn how to use a for loop in Python with various examples.
for item in Iterable-Object: # Statement 1 # Statement 2 #....... # Statement N # Statement Outside of loop body
The body of loop decides by the indentation.
Nested Loop – Loop within a loop
In nested loop and loop body have another loop inside. There can be any level of nested code. Following syntax for a simplest nested loop. Again the indentation is used to discriminate the two loop’s body.
for item_1 in Iterable-Object_1: # Outer Loop for item_2 in Iterable-Object_2: # Inner Loop # Statement 1 - Inner Loop # Statement 2 - Inner Loop #....... # Statement N - Inner Loop # Statement 1 - Outer Loop # Statement 2 - Outer Loop #....... # Statement N - Outer Loop # Statement Outside of all loops body
Loop example using a list –
# Example Program to Iterate a List #Using for loop. Program myList = [100, "Python", 3, "For Loop"]; for ele in myList: print(ele); print("Done with for loop");
Output- 100 Python 3 For Loop Done with for loop
- Creates a list sequence of name myList and Initializes with 4 items.
- The for loop traverse the sequence and hold each item in ele while traversal.
- Prints the item till reaches the end of the list.
- After printing the last item, control comes outside the loop.
Loop for a larger number of iterations?
In the above example, we have seen that a list is created. What if we want to execute a loop for a very large number of times say 50000000?. Do we need to create a list that long? No, we have a built-in function range(). With range we can create a sequence, just passing a number. The following example executes a for-loop ten times using the range() function.
# Example Program to Iterate #Using for loop with range() function. Program for ele in range(10): print(ele); print("Done with for loop");
0 1 2 3 4 5 6 7 8 9 Done with for loop
- The range(number) function returns an object for iterable sequence. The values in sequence start from zero and end with the number -1.
- There are other variants are also for range function. That we will discuss in another python tutorial.
One More Example – Calculate the Length of string using for loop.
# Example Program to Iterate a string and calculate the length myString = "Learn Python String"; len = 0; for ele in myString: len = len + 1; print("Length of string = ", len);
Done with for loop : Length of string = 19