How To Use A For Loop In Python

One of the most essential features of any programming language is its ability to iterate over a sequence or collection of values.

This repetitive process allows you to perform operations on each item or element in the sequence. In Python, one of the easiest and most popular methods to iterate over a collection is by using a for loop.

In this tutorial, we will cover how to use a for loop in Python and what you can do with it.

Understanding the For Loop Syntax

The basic syntax for a for loop in Python is as follows:

Here, the iterable is a sequence (like a list, tuple, or string) or collection (like a dictionary or set), and the variable represents each element in the iterable. The code within the loop (indented) is executed for each element in the iterable.

Iterating Over a List

Let’s start with a simple example: iterating over a list of numbers and printing each one.

The output will be:

1
2
3
4
5

Iterating Over a String

Strings are also iterables, and you can loop through each character in a string:

The output will be:

P
y
t
h
o
n

Using the range() Function

Python provides a built-in function called range() that generates a sequence of numbers. The range() function is commonly used along with the for loops.

The syntax for the range() function is as follows:

Here is how you would use a range() function with a for loop to print the first five natural numbers:

The output will be:

1
2
3
4
5

Full Code Examples

Example 1: Iterating Over a List

Example 2: Iterating Over a String

Example 3: Using the range() Function

Conclusion

In this tutorial, we learned how to use a for loop in Python to iterate over various types of iterables, such as lists and strings.

We also learned how to use the built-in range() function to generate sequences of numbers. With these tools in your Python programming toolbox, you can handle various tasks that involve repetitive execution of code for each element in your dataset.