Reading Time: 7 minutes

What is a For Loop?

python-logo

A for loop in Python is utilized to make repeated use of a function or procedure, applying it each time to the result of the previous sequence. This repeating process is called iteration. The for loop checks each iteration until a condition is met. Typically these are used when we have to run a block of code duplicating it X number of times. Each time it iterates over a sequence, it re-executes the code.

Syntax of a For Loop

The typical syntax of a for loop in a python script is seen below.

#!/usr/bin/python3
for a in sequence:
body of for

How Does a For Loop Work

Multiple languages have for loop syntax options within their code. In Python, any object with a method that is iterable can be utilized in a for loop. An iterable method is defined as data presented in the form of a list, where multiple values exist in an orderly manner. We can also define our iterables arrays by creating objects using the next() or iter() methods.

Code Examples

Using a Simple For Loop

A Pythonfor statement runs a sequence of code over and over again, in order, executing the same code block each time. This function allows us to re-run a command X number of times until we reach the desired result. The alternative looping command uses the while statement. Both of these constructs are used for different purposes. Here, we use (0,3) to determine the number of iterations to run.

#!/usr/bin/python3
#simple for loop example
for x in range(0, 3):
        print("Loop %d" % (x))

The command’s output is below.

root@host:~# python forloop1.py
Loop 0
Loop 1
Loop 2
root@host:~#

We can see that the for loop runs for a fixed number of iterations (0, 3) while adding a number for each loop completed. In the next example, the while statement (using the boolean value True) never changes.

Using a Range Statement in a For Loop

The range() function has two main sets of parameters:

  • range(stop) - Stop indicates the quantity of whole numbers (or integers) to render, starting from 0.  
  • range([start], stop[, step])
  • start: This is the beginning number of the sequence.
  • stop: Numbers are generated up to, but not including, this number.
  • step: The difference between the numbers within the sequence.

Employing the range() function in a script, we can define a set number of loops to iterate through that sequence. As an example, we can define the range as range(12). Because Python defines 0 as the first number in a range (or list of indexes), our example range is 0 to 11, not 1 to 12. Python is 0-index based. This means that a list of indexes begins at 0, not 1. Lastly, users should note that all parameters should be positive or negative integers. 

As an example, specifying the start and stop points in a range() function like the one below, a list will be generated from 4 to 7 (5 numbers).

range(4,7)

Using the forloop4.py script, we can generate a two-parameter range.

#!/usr/bin/python3
for i in range(4, 7):
     print(i)

The script output is below.

root@host:~# python forloop4.py
4
5
6
root@host:~#

Using the following forloop3.py script, we can output a single list of numbers 0-6.

#!/usr/bin/python3
for i in range(7):
     print(i)

The script output is below.

root@host:~# python forloop3.py
0
1
2
3
4
5
6
root@host:~#

Using this same method, we can use the forloop5.py script to increment a list of negative numbers, going by threes.

#!/usr/bin/python3
for i in range(0, -12,  -3):
     print(i)

The script output is below.

root@host:~# python forloop5.py
0
-3
-6
-9
root@host:~#

Using a While Statement in a For Loop

Should we choose to loop a command forever, we can use a while statement in a script like the one below to repeatedly rerun a simple command.

Note:
If you create this script and run it, it WILL run extremely quickly. Our script ran over 54,000 iterations in less than a second before we were able to hit CTRL+C to end the run.
#!/usr/bin/python3
#simple for loop example
x = 1
while True:
        print("Loop number %d " % (x))
            x += 1

The script output is below.

root@host:~# python forloop2.py
Loop number 1
Loop number 2
Loop number 3 
. . . 
Loop number 54345
Loop number 54346
Loop number 54347
Loop ^C
Traceback (most recent call last):
  File "forloop2.py", line 5, in <module>
    print("Loop number %d " % (x))
KeyboardInterrupt
root@host:~#

The initial for loop runs a fixed number of times, so it ran three times in this case. Meanwhile, a while loop runs until the loop condition changes or is acted upon by a limiter. 

Using a Loop Statement on a For String

Strings can produce a succession of characters because they are considered iterable objects. Using the forloop6.py script, we can list the string in a sequence.

#!/usr/bin/python3
for x in "watermelon":
    print(x)

The script output is below.

root@host:~# python forloop6.py
w
a
t
e
r
m
e
l
o
n
root@host:~#

Using a Break Statement in a For Loop

When using a break statement, we can stop a loop before it has a chance to loop through all our listed items. Using the forloop7.py script, we can terminate the script when the loop reaches the Chevy entry.

#!/usr/bin/python3
cars = ["Ford", "Chevy", "GM"]
for x in cars:
   print(x)
   if x == "Chevy":
     break

The script output is below.

root@host:~# python forloop7.py
Ford
Chevy
root@host:~#

Using a Continue Statement in a For Loop

If we use the continue statement, we can cease the current iteration loop and continue with the following entry. Using the forloop8.py script that employs our previous cars example will stop the current iteration loop and continue with the next entry in the list.

#!/usr/bin/python3
cars = ["Ford", "Chevy", "GM"]
for x in cars:
   if x == "Chevy":
     continue
   print(x)

Output

root@host:~# python forloop8.py
Ford
GM
root@host:~#

Using an Else Statement in a For Loop

The else statement in a for loop runs a specific block of code when the loop completes. Using the forloop9.py script, we can output a range and then print the message “Done” when it finishes. Users should note that the else block will not be executed if a break statement halts the running loop.

#!/usr/bin/python3
for x in range(5):
  print(x)
else:
  print("Done.")

Output.

root@host:~# python forloop9.py
0
1
2
3
4
Done.
root@host:~#

Using a Nested Loop Inside a For Loop

A nested loop is simply a loop within a loop. The inside loop will run once for each iteration of the outer loop. Using the forloop10.py script, we 

#!/usr/bin/python3
adj = ["Blue", "Yellow", "Red"]
cars = ["Ford", "Chevy", "GM"]

for x in adj:
  for y in cars:
    print(x, y)

Output.

root@host:~# python forloop10.py
('Blue', 'Ford')
('Blue', 'Chevy')
('Blue', 'GM')
('Yellow', 'Ford')
('Yellow', 'Chevy')
('Yellow', 'GM')
('Red', 'Ford')
('Red', 'Chevy')
('Red', 'GM')
root@host:~#

Using a Pass Statement in a For Loop

Technically, for loops should not be left empty. If we must leave a for loop empty, we can use a pass statement to prevent errors. Using the forloop11.py script, we should get no output at all when running our script.

#!/usr/bin/python3
for x in[1, 2, 3]:
  pass

Output.

root@merovingian2:~# python forloop11.py
root@merovingian2:~#

If we remove the pass statement, here is the output. 

root@host:~# python forloop11.py
  File "forloop11.py", line 3

                      ^
IndentationError: expected an indented block
root@host:~#

10 Real-World Uses of For Loops

The examples below (or some iteration of) are often used in everyday Linux administration. Some of them may be old or reference functions that are no longer available, but they are listed to show the versatility of using a for loop in a script or terminal. Below, we rename all the files in a folder to file1, file 2, etc...

j=1; for i in *; do mv "$i" File$j; j=$((j+1)); done

Change the ownership for everything under the directory agora/ for all users in the public_html/agora folder

for i in `ls -1 /var/cpanel/users/`; do chown -R $i. /home*/$i/public_html/agora/*; done

Sometimes semaphores get stuck when Apache fails to clean up after itself. Below, we run the ipcs -s command to check on this. Clear them out with this command.

for i in `ipcs -s | awk '/httpd/ {print $2}'`; do (ipcrm -s $i); done
Note:
The command below is to clean out a specific folder. Use with caution as we are using the rm command.
for i in $(ls -A .); do rm -f $i; done  -

This is how to check for a particular account backup in daily/weekly/monthly folders if present, all at the same time.

for i in $(find /backup/cpbackup/ -type d | grep -i [A-Z]);do ll $i| grep -i <keyword>; done

Below shows how we can to optimize all tables in a database. 

for i in $(mysql -e "show databases;" | sed 's/Database//') ; do for each in $(mysql -e "use $i; show tables;" \
| sed 's/Tables.*//' ;) ; do mysql -e "use $i ; optimize table $each" ; done ; done

Before cPanel had a visual SPF installer in WHM, we used this command to add SPF records.

for i in `ls /var/cpanel/users` ;do /usr/local/cpanel/bin/spf_installer $i ;done

Or, if we wanted to install both SPF and DKIM records, we used this command.

for i in `ls /var/cpanel/users|grep -v "./"`; do /usr/local/cpanel/bin/dkim_keys_install &&  /usr/local/cpanel/bin/spf_installer $i ; done ;

Here, we use a for loop to search the exim mainlog for a sender who was using three specific domains via their IP, and once found, block them in the firewall while adding a comment.

for i in $(grep -i sendername /var/log/exim_mainlog |egrep 'domain.com| domain.net | domain.org | grep "<="| egrep "([0-9]{1,3}\.){3}[0-9]{1,3}" -o | grep -v 72.52.178.16 | sort |uniq); do csf -d $i per ticket 4224475 for sending spam ;done

Here we use a for loop to kill -9 nobody PHP processes and then restart apache.

for i in $(ps aux |grep nobody |awk '{print $2}');do kill -9 $i;done && service httpd restart

Conclusion

As we can see, for loops are used in multiple situations directly from the commandline or in a script. To recap, a for loop is a flow control statement used to continuously iterate a specific code block repeatedly for a fixed number of times. We define this Python statement which frequently performs a set of conditions until acted upon by an external state or influence. Overall, Python for loops offers some of the most useful options in a modern programming language. 

We pride ourselves on being The Most Helpful Humans In Hosting™!

Should you have any questions regarding this information, we will always answer any inquiries regarding this article, 24 hours a day, 7 days a week, 365 days a year.

If you are a Fully Managed VPS server, Cloud Dedicated, VMWare Private Cloud, Private Parent server, Managed Cloud Servers, or a Dedicated server owner and you are uncomfortable with performing any of the steps outlined, we can be reached via phone at @800.580.4985, a chat or support ticket to assisting you with this process.

About the Author: David Singer

I am a g33k, Linux blogger, developer, student, and former Tech Writer for Liquidweb.com. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Have Some Questions?

Our Sales and Support teams are available 24 hours by phone or e-mail to assist.

1.800.580.4985
1.517.322.0434

Latest Articles

What is a Webhook?

Read Article

Microsoft Exchange Server Security Update

Read Article

How to Monitor Your Server in WHM

Read Article

How to Monitor Your Server in WHM

Read Article

How to Fix Typical WordPress Errors

Read Article