This Python ‘for loop’ guide will not only show you how to construct a ‘for loop’ in Python, it will also provide an equivalent example in another common language for additional clarity.
For loops in Python serve the same purpose as they do in every other coding language, which is to iterate through data in some shape or form and then stop at a specified point in that data.
Python For Loop Example
for i in range(10): print('This string will be displayed 10 times')
The first line tells the code following it to execute 10 times, as specified as a parameter to the ‘range‘ function called. If you want it to execute 5 times, change ‘range(10)’ to ‘range(5)’. Notice that I left an empty line after the last line of code, which you should do when writing Python.
The JavaScript example of the loop above is:
for (let i = 0; i < 10; i++) {
console.log('This string will be printed 10 times');
}
You can also make it loop until you have reached the end of an array. The example array used below ‘testarray’, has three members, so it will loop 3 times. It uses the ‘len()’ function to retrieve the length of the array.
For example:
testarray = ['cat', 'bird', 'orange'] for i in range(len(testarray)): print('This string will be displayed 3 times because there are three members in testarray')
Now let us extract data from the array and stop it when the end of the array has been reached:
testarray = ['cat', 'bird', 'orange'] for i in range(len(testarray)): print(testarray[i])
The code above will print whichever array member it is currently on while it is looping, and will continue to loop until it reaches the end of that array. This is how you print all members of an array in Python.
Now for a more useful, but simple implementation. Let us check to see if ‘testarray’ contains a cat. You could use an ‘if’ statement to do that while iterating through the array as shown in the following example:
testarray = ['cat', 'bird', 'orange'] for i in range(len(testarray)): if testarray[i] == 'cat': print(testarray[i])