Skip to main content
HomeAbout PythonLearn Python

For Loops in Python Tutorial

Learn how to implement For Loops in Python for iterating a sequence, or the rows and columns of a pandas dataframe.
Jul 2019  · 5 min read

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.

Start Learning Python For Free

Intermediate Python

Beginner
4 hr
927.9K learners
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

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.

Python Courses

Introduction to Python

Beginner
4 hr
4.8M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

How to Create a Data Analyst Resume

In this article, we'll discuss how to create a data analyst resume that will get you hired.
Matt Crabtree's photo

Matt Crabtree

7 min

Building Your Data Science Portfolio with DataCamp Workspace (Part 1)

Learn how to build a comprehensive data science portfolio by exploring examples different examples, mastering tips to make your work stand out, and utilizing the DataCamp Workspace effectively to showcase your results.
Justin Saddlemyer's photo

Justin Saddlemyer

9 min

Pandas 2.0: What’s New and Top Tips

Dive into pandas 2.0, the latest update of the essential data analysis library, with new features like PyArrow integration, nullable data types, and non-nanosecond datetime resolution for better performance and efficiency.
Moez Ali's photo

Moez Ali

9 min

Building a Safer Internet with Data Science

Learn the key drivers of a data strategy that helps ensure online safety and consumer protection with Richard Davis, the Chief Data Officer at Ofcom, the UK’s government-approved regulatory and competition authority. 
Adel Nehme's photo

Adel Nehme

43 min

Conda Cheat Sheet

In this cheat sheet, learn all about the basics of working with Conda. From managing and installing packages, to working with channels & environments, learn the fundamentals of the conda package management tool suite.
Richie Cotton's photo

Richie Cotton

Matplotlib time series line plot

This tutorial explores how to create and customize time series line plots in matplotlib.
Elena Kosourova's photo

Elena Kosourova

8 min

See MoreSee More