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:
1 2 |
for variable in iterable: # Code to be executed |
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.
1 2 3 4 |
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num) |
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:
1 2 3 4 |
text = "Python" for char in text: print(char) |
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:
1 2 3 |
range(stop) # generates numbers from 0 to stop-1 range(start, stop) # generates numbers from start to stop-1 range(start, stop, step) # increment by step instead of 1 |
Here is how you would use a range() function with a for loop to print the first five natural numbers:
1 2 |
for i in range(1, 6): print(i) |
The output will be:
1 2 3 4 5
Full Code Examples
Example 1: Iterating Over a List
1 2 3 4 |
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num) |
Example 2: Iterating Over a String
1 2 3 4 |
text = "Python" for char in text: print(char) |
Example 3: Using the range() Function
1 2 |
for i in range(1, 6): print(i) |
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.