Lesson 8: Python For Loop

Loop is a very powerful concept in programming and it allows to execute a task in iterations. Repeating a task or a function for a desired number of times can have many benefits.

In this lesson we will look at Python For Loops.

It can be best explained over a Python example:

>>> for iterator in iterable:
>>>     execute task

In a simplified sense, we see three somewhat trivial parts, these are “for”, “in” and “:” in the little code piece above. These are parts of the for loop syntax in Python and they never change. We also see three parts that can change in every different for loop. These are:

  • iterator: is a variable we named and it is used to iterate through the collection (list, dict, tuple, range object or something of that sort).
  • iterable: is a sequence or collection through which iteration happens in for loops.
  • task: this is the part where code executes a task or a function. It’s also what happens during each iteration in the loop. Also please note that this part is always indented by a tab character (sometimes 4 space characters instead of tab on some platforms).

Used Where?

Loops are great tools for handling repetitive tasks. They can be used for:
  • Processing each element of a sequence
  • Printing each element of a sequence
  • Executing a function or another program for each element in a sequence
  • Accumulating data
  • Doing analysis through a Data Frame in data science.

To give just a few examples.

For loops are also commonly used in other programs, libraries, servers in the back end etc. we normally don’t see this because it is in the source code and we use the end product. If you were to check source code for open source libraries such as pandas, numpy, scipy, matplotlib, scikit-learn, PIL etc. you would very likely see multiple for loops being utilized behind the curtains.

Syntax do(s)

1) First line starts with for

2) There is a colon(:) at the end of first line

3) After first line following lines should be indented

Syntax don't(s)

1) Don't forget the colon (:) at the end of the first line

2) Don't forget the indent after the first line

Example 1: Printing a value with for loop

for iter in [1,2,3]:
    print("Hello World!")

“Hello World!”
“Hello World!”
“Hello World!”

In this example <iter> is just a variable we named. Python list has 3 elements [1,2,3]. So for each value (or iter) “Hello World!” is printed once. 

Example 2: For loop with range function

Range objects can be perfect iterables when you need a range of numbers. Using range function we can create a range object and using Python’s for loop we can iterate through it. Also in this example using print function we are executing a print command in each iteration but it could be some other task also.

Check out the example:

for iter in range(3):
    print(iter)

0
1
2

We are directly printing the iterator which takes different values during its iteration through the range(3) object which consists of 0,1 and 2.

We have a Python lesson on range function in case you need to review it.

Example 3: Iterating through a list using for loop in Python

Let’s do something slightly more complicated. This fresh fruit company adds three digits to their inventory items to indicate availability. 999 means available for any quantity while 000 means unavailable.

Can you check last three digits of each item in the first list and add the name (without digits) of available items to the second list for order?

lst = ["apple999", "kiwi999", "strawberry000", "tangerine999"]
lst2 = []

for iter in lst:
    if int(iter[-3:]) == 999:
        (lst2.append(iter[:-3]))

print(lst2)

apple
kiwi
strawberry

Here we are practicing multiple fundamental Python concepts yet again. Starting with Python lists and Python for loop, we have slicing notation, list methodsconditional statement and Python operators.

If Loops are a new concept to you, we highly recommend you to copy lst and lst2 and try to code the rest on your own at least a few times. You can even do this as a morning routine for a few days/weeks until it becomes a very natural instinct for you. This will ensure for you to gain solid for loop skills for the rest of your life.

Example 4: For loop with range function

a = 10
for iter in range(5):
    a = a+5

    print(a)

35

We have created a variable with initial value of 10. And each time the loop runs, a gets assigned to its initial value plus 5.

In the next iteration its initial value becomes plus 5 and so on. After 5 total iterations loop stops and final value of a is 35.

Also print() function is not inside the loop so nothing gets printed during the loop, but a’s value becomes updated behind the curtain with each iteration.

Tips

1- For loop is usually more useful when you know the exact iteration time before the loop. When you’re iterating through sequences like lists, tuples, dictionaries, strings and ranges, since you know the length of the sequence already it usually makes more sense to utilize a for loop.

Function : len

We will utilize Python’s handy len function and find out each strings length in a list.

Example 5:

Let’s see how the name lengths for these delicious Mexican peppers compare.

Check out this example, we are using len function to print lengths of each item during the iteration.

for i in ["Jalapeno", "Serrano"]:
    print(len(i))

8
7

The winner is Jalapeno!

Advanced Concepts (Optional)

Nested For Loop

1- In some situations you might need a nested loop structure. We have previously seen that lists can be consisted of many type of different data including other lists. Let’s see an example of nested list and nested for loop.

Example 6: Nested for loop in Python

Here we have a parent list which consists of two nested lists in it. Let’s see a simple Python code example where we iterate through the inner elements of the inner lists.

lst = [[1,2,3], ["land", "sea", "sky"]]
for i in lst:
    for j in i:
        print(j)

1
2
3
land
sea
sky

  • In the first iteration, i gets assigned to first element in a (which is the list: [1,2,3]) and then j gets assigned to each element in i (which are integers: 1,2 and 3)
  • In the second iteration, i gets assigned to second element in a ([“land”, “sea”, “sky”]) and then j gets assigned to each element in i (“land”, “sea”, “sky”)
Now, how about printing in following format?
1: land
2: sea
3: sky
Can you achieve this without looking at the example below? You can simply do it by accessing the second list via its index.

Example 7: Nested list iteration with for loop in Python

Let’s try to access second list’s elements using first lists values during the iteration just for fun and practice.

lst = [[1,2,3], ["land", "sea", "sky"]]
for i in lst[0]:
    print(i, ": ", lst[1][i-1])

1 : land
2 : sea
3 : sky

  • Here, it happens so that first list’s elements are convenient enough to make them index access elements for the second list in the code. But if this wasn’t the case we could still simply create an extra counter (maybe named c) and access second list’s elements at each iteration that way.

For loop is a very convenient and easy to use loop concept in Python. Loops are extremely powerful because they enable automation through iteration, they can be used to handle repetitive tasks, they can be utilized to create intelligent functions and take care of many different tasks. Feel free to visit this article: For a simple yet Practical Python examples with For Loops.

We have some interactive Python exercises to help you practice this important programming topic. Take your time and make sure you are comfortable with loops which will be a really empowering step in your amazing coding future.

In the next lesson we will see Python while loops. You will see how while loops are another brilliant loop solution in Python. While loops compliment For Loops very well and they can be used to do certain type of iterations better than for loops.

I hope this was useful and productive for your learning. 👨‍🎓

Next Lesson: While Loop