Python For loops


Python For loops Author: Mohammad Amaan Abbasi | July 12, 2018

This article will walk you through For Loops in Python. This post suites to people who have a little programming experience with C,C++ or python.

If you are coming from C or C++ background you probably have seen for loops.
Let’s do a recap first, before we get started.Firstly in a C++ loop, we initialize a variable(i), then we put a condition(i<=n) and Lastly, increements the variable.

Example:

for(int i = 0; i <= 5; i++){

    cout << i << endl;
}

Output

0 
1 
2
4
5

However, the code above will make no sense to a person who have never done programming before. It is not readable at all. So python comes to the rescue.
Let us now look at the equivalent python syntax.

for number in range(0,6):
    print(number)

Isn’t this loop much more readable than the previous one? Of course, it makes much more sense. Let me explain it to you- for number in range(0,6) , so we are looking for a number in range of numbers between 0-6, and printing it to the screen, Easy enough.

Did you notice the number variable, it was not intialized, yet the program worked, but in C++ or C it is mandatory to initialize variables with a datatype before they can be used. In python, we didn’t have to initialize variables with a datatype. It is a upside but also a downside of python, But that is a topic for another day.

Let’s take a look at another example.

Suppose we have a list of names-names = ['Daniel,'Mike,'Ahmad'] and we want to print it.

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Unlike other data-structures like arrays list can store different types(data-types) of elements in them. Examples of lists:
[1,2,3,4,5],
[‘Rosy’,10,34.6,“Ali”]

If you are coming from C++ background then you might do something like:

names = ['Daniel,'Mike,'Ahmad']

i = 0
while i < len(names):
    print(names[i])
    i += 1

But that is so unpythonic

Two things could be improved in this code example:

First, it keeps track of the index i manually—initializing it to zero and then incrementing it upon every loop iteration.
And second, it uses len() to get the size of the list in order to determine how often to iterate.
In Python you can write loops that handle both of these responsibilities automatically. It’s a great idea to take advantage of that.

The python way of writing the loop is:

names = ['Daniel','Mike','Ahmad']

for name in names:
    print(name)

Takeaway

  • Avoid using C++ style for loops in python because they are considered unpythonic.
  • Python for loops don’t need index variable, they can directly iterate over lists.

Learning Resources