For Loops—Python

Python has a for loop which is allows us to step through each element in an iterable (generally anything that defines __iter__ or __getitem__ such as files, lists, tuples, etc.).

First let’s go through an example of a for loop

for i in range(10):

When run, this code produces the following output


Let’s discuss how this works. Our loop begins with the keyword for followed by a variable or variables. After the variable, we have the in keyword followed by an iterable. The loop continues until there are no more items in the iterable.

In our example, the iterable is the range function. So when we have range(10) we are making a sequence of ten numbers 0-9. Everytime range produces a number, it gets assigned to the variable i. We then use print(str(i)) to print the value of i to the console.

Here is another demonstration of the for loop, this time using a list

names = ['Bob', 'Tina', 'Gene', 'Linda']

for name in names:

Lists implement the correct protocals that allow them to be used in for loops. In this case, we populate a list with some names. Everytime the loop executes, the name variable is updated with the next name in the list. We then print the name to the console.

The for loop let’s us have more than one variable in the loop.

names = [['Bob', 'Belcher'], 
        ['Tina', 'Belcher'], 
        ['Gene', 'Belcher'], 
        ['Linda', 'Belcher']]
for fname, lname in names:
    print(fname, ' ', lname)

Keep in mind that when you do this, your update variables need to match the number of variables in your sequence. So if we had three variables here, we would get an exception.


7 thoughts on “For Loops—Python”

  1. This is very helpful, thank you! I just learned about the for and in keywords today to use loops on lists. Your explanation is clear and fun! 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s