Tutorials
must read
pandas
+2

For Loops in Python

Learn how to implement For Loops in Python for iterating a sequence, or the rows and columns of a pandas dataframe.

Introduction

Like other programming languages, for loops in Python are a little different in the sense that they work more like an iterator and less like a for keyword. In Python, there is not C like syntax for(i=0; i<n; i++) but you use for in n.

They can be used to iterate over a sequence of a list, string, tuple, set, array, data frame.

Given a list of elements, for loop can be used to iterate over each item in that list and execute it.

To iterate over a series of items For loops use the range function. The range function returns a new list with numbers of that specified range based on the length of the sequence.

While iterating over a sequence you can also use the index of elements in the sequence to iterate, but the key is first to calculate the length of the list and then iterate over the series within the range of this length.

The for loops in Python are zero-indexed.

Let's quickly jump onto the implementation part of it.

Implementing Loops

To start with, let's print numbers ranging from 1-10. Since the for loops in Python are zero-indexed you will need to add one in each iteration; otherwise, it will output values from 0-9.

for i in range(10):
    print (i+1)
1
2
3
4
5
6
7
8
9
10

Let's iterate over a string of a word Datacamp using for loop and only print the letter a.

for i in "Datacamp":
    if i == 'a':
        print (i)
a
a
a

Let's say you want to define a list of elements and iterate over those elements one by one.

sequence = [1,2,8,100,200,'datacamp','tutorial']
for i in sequence:
    print (i)
1
2
8
100
200
datacamp
tutorial

But what if you want to find the length of the list and then iterate over it? You will use the in-built len function for it and then on the length output you will apply range.

Remember, the range always expects an integer value.

for i in range(len(sequence)):
    print (sequence[i])
1
2
8
100
200
datacamp
tutorial

Great! But why do you need to use the len function when you can directly use for i in numbers? The answer is simple. What if you would like to modify or work with the indices of the sequence like changing the element of an existing list, then you would need range(len(sequence)).

for i in range(len(sequence)):
    element = sequence[i]
    if type(element) == int:
        sequence[i] = element + 4
sequence
[5, 6, 12, 104, 204, 'datacamp', 'tutorial']

Cool, isn't it? You were able to modify the elements of the list based on the if condition.

Let's now see how you can print odd numbers between 1 - 20. To accomplish this, you will have to define three things in the range function. The starting point, the ending point and the increment value (or steps) at which the loop will increment over the numbers 1 - 20.

for i in range(1,20,2):
    print (i)
1
3
5
7
9
11
13
15
17
19

Nested For loop

for i in range(11):
    for j in range(i):
        print (i, end=' ')
    print()
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10

For loop to iterate over rows and columns of a dataframe

import pandas as pd
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
iris.head()
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
len(iris)
150
for i in range(len(iris)):
    Class = iris.iloc[i,4]
    if Class == 'versicolor' and i < 70:
        print (Class)
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor
versicolor

Next, let's add two to every row of columns sepal_length,sepal_width, petal_length and petal_width.

columns = ['sepal_length','sepal_width','petal_length','petal_width']
for indices, row in iris.iterrows():
    for column in columns:
        iris.at[indices,column] = row[column] + 2
iris.head()
sepal_length sepal_width petal_length petal_width species
0 7.1 5.5 3.4 2.2 setosa
1 6.9 5.0 3.4 2.2 setosa
2 6.7 5.2 3.3 2.2 setosa
3 6.6 5.1 3.5 2.2 setosa
4 7.0 5.6 3.4 2.2 setosa

Iterating over a sequence with Lambda function

Python's lambda function is fast and powerful as compared to the basic for loop. It is widely used, especially when dealing with Dataframes. You can process your data with the help of Lambda function with very little code. Although, it sometimes becomes difficult to understand it.

x = [20, 30, 40, 50, 60]
y = []
for v in x :
    y += [v * 5]
y
[100, 150, 200, 250, 300]

Now, let's try this with a lambda and map function.

Map takes in a function, for example, a lambda function and a sequence x and then returns a new sequence.

y = map(lambda x: x * 5,x)
y
<map at 0x11be7cc88>

It returns a generator function and to get the output from the generator; you pass the output as an argument to list.

list(y)
[100, 150, 200, 250, 300]

Now, let's take a step back and look at both the for loop way and lambda/map() combination. You will notice that the difference between the two is adding map, lambda, and removal of "for" and "in". And also, within one line, you were able to code it.

Conclusion

Congratulations on finishing this basic Python For loop tutorial.

For loops are the backbone of every programming language and when it is Python, using For loops are not at all hard to code, and they are similar in spirit to writing an English sentence.

If you want to learn more about for loops in Python, take DataCamp's Python Data Science Toolbox (Part 2) course.

Please feel free to ask any questions related to this tutorial in the comments section below.

Want to leave a comment?