One of the most interesting concepts in programming languages is loops. Imagine you’re faced with a task. It’s simple but repetitive, like counting from 1 to 100. Now, you could do this manually, one number at a time. But that would be time-consuming and not particularly efficient. This is where loops in programming come in.
A loop is a control structure that allows you to repeat a set of instructions until a certain condition is met. The condition could be anything: a certain number of repetitions, a particular state of data, or even an external event. A Python For Loop is a special kind of loop used when you know the exact repetitions for a loop.
You use for loops in your code to simplify the process of iterating over a sequence or collection of elements. This can be a list, a string, a dictionary, a set, or any other iterable object in Python.
By using a for loop, you can execute a block of code for each item in the sequence. For example, if you need to print all the elements in a list, instead of writing a print statement for each item, you can just use a for loop. This makes your code more efficient, readable, and less prone to errors.
Before you start writing for loops, you must understand the basics. In this article, we’ll look at the syntax for Python for loops, the terminology used when working with them, and how to use them in different scenarios.
Let’s get into it!
What is the Syntax for Python For Loops?
In Python, for loops are used to iterate over iterable objects. The basic syntax of a for loop is as follows:
for variable in iterable:
# code to execute for each item
In this syntax, ‘variable’ is the name you choose for the current item in the iteration. ‘Iterable’ is the sequence or collection of items you want to iterate over.
The code inside the loop, denoted here as ‘# code to execute for each item’, is the action you want to perform for each item in the iterable.
The below example shows a basic for loop in Python:
cities = ['New York', 'London', 'Paris', 'Tokyo']
for city in cities:
print(city)
In the above example, ‘city’ is the variable, and ‘cities’ is the iterable. The code inside the loop is print(city), which prints each city in the list.
Python Iterables and Iterable Objects
Another crucial concept to understand when working with loops is the concept of iterables and iterable objects.
In Python, an iterable is any object capable of returning its elements one at a time. This means you can pass through the iterable object using a method like a loop.
Common examples of iterable objects that you’ll encounter include lists, strings, tuples, and dictionaries.
For example, when you create a list of numbers like [1, 2, 3, 4, 5], you can iterate over each number in the list. Each number is an element of the iterable list.
Similarly, if you have a string such as ‘hello’, you can iterate over each character in the string. In this case, the string is the iterable, and each character (‘h’, ‘e’, ‘l’, ‘l’, ‘o’) is an element of the iterable.
Below, you will find some examples of using for loops with different iterables.
1. Looping Through a List with a Python For Loop
In Python, a list is a type of data structure that can hold an ordered collection of items, which means you can store all sorts of objects — integers, floats, strings, and even other lists or complex objects.
To loop through a list with a for loop, you can use the following code:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This code will print all the fruits in the list of fruits as shown below:
2. Looping Through a Tuple with a Python For Loop
A tuple in Python is a collection of objects that are ordered and immutable. This means that, once a tuple is created, you cannot change its content.
To look through a tuple with the for loop, you can use the following Python code:
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
The for loop will go through all the elements of the tuple and print them to the screen as shown in the image below:
3. Looping Through a Dictionary with a Python For Loop
A dictionary in Python is an unordered collection of data stored as a key and a value. This is also known as a key-value pair.
To loop through a dictionary with the for loop, you can use the following Python code:
student = {'name': 'John', 'age': 24, 'course': 'Computer Science'}
for key, value in student.items():
print(key, value)
The for loop will iterate through all the key-value pairs in the dictionary and will print them to the screen as shown below:
4. Looping Through a String with a Python For Loop
A string in Python is a sequence of characters. Strings are used in Python to record textual information as well as arbitrary collections of bytes (such as an image file’s contents).
To loop through a string in Python using the for loop, you can use the code given below:
greeting = "Hello, world!"
for char in greeting:
print(char)
The for loop will print every alphabet in the string to the screen as shown below:
The examples above show how loops are helpful when iterating over different data types. You can also control the functionality of your for loops by using functions and statements within your loop.
Let’s look at some key functions and statements that are frequently used with for loops in the next section.
Key Functions and Statements in Python For Loops
When you are using for loops, functions and statements can improve your control over the loop and make your code more efficient and easier to read.
We have listed the key functions and statements used in for loops below:
1. How to Use Range() Function with a Python For Loop
The range() function allows you to generate a sequence of numbers. It is generally used for iterating a specified number of times.
The basic syntax is:
for i in range(start, stop, step):
# your code here
start: an optional parameter specifying the starting point; by default, it is 0.
stop: a required parameter that defines the endpoint (exclusive).
step: an optional parameter indicating the increment, with a default value of 1.
To give you a clear understanding of the range function, take a look at the example below where we print numbers from 1 to 5 using the range function with a for loop:
for i in range(5):
print(i)
2. How to Use the Break Statement with a Python For Loop
The break statement allows you to exit a for loop when a certain condition is met. When the break keyword is reached in the loop body, the loop stops immediately.
The following is an example of the for loop with a break statement:
for i in range(10):
if i == 5:
break
print(i)
This code is a loop running from 0 to 9. If the current number is 5, it immediately stops the loop using break. So, it only prints the numbers from 0 to 4. When it hits 5, it stops and doesn’t print any more numbers.
3. How to Use the Continue Statement with a Python For Loop
The continue statement is used to skip the current iteration and jump to the next one.
The following is an example of a continue statement with for loop:
for i in range(5):
if i == 3:
continue
print(i)
The loop iterates from 0 to 4. If the current number is 3, we skip it before completing the rest of the loop for that iteration using continue. This means you print all numbers from 0 to 4, except for 3.
Notice in the image above that the number 3 is skipped due to the continue statement.
4. How to Use the Pass Statement
The pass statement is a placeholder that intentionally does nothing. It can be used when you need the loop structure but don’t have any specific code to execute within it yet.
The following is an example of a pass statement with a for loop:
for i in range(5):
pass
This loop won’t output anything, as the pass statement is a placeholder for future code. Loops are flexible and can be adjusted to fit any use case, such as using loops with the else block of code.
If you’d like to get hands-on practice with for loops, check the following video out:
As you start writing for loops, you will eventually want to jump into the advanced techniques in for loops. Knowledge of the advanced techniques will allow you to write more efficient for loops for almost any use case.
Let’s look at some of the advanced techniques in for loops in the next section!
3 Advanced Techniques Using Python For Loops
As a Python programmer, you often need to deal with collections of items, like lists or strings, and perform operations on each item. To perform these operations, you’ll need to have a basic understanding of the advanced techniques in for loops.
In this section, we’ll explore some advanced techniques for using for loops in Python. We’ll cover nested loops, list comprehensions, and the enumerate() function.
1. How to Use Nested Python For Loops
There are times when you need to loop over multiple dimensions of data, like a matrix or a list of lists. In such cases, you can use nested loops, which is a loop inside another loop. A nested loop allows you to traverse multiple dimensions of data effectively.
The following is an example of a nested for loop:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for val in row:
print(val, end=' ')
print()
In this code, we are using a nested loop to print each number in a matrix. The outer loop goes over each row, and the inner loop goes through each number in that row.
After printing each row, we start a new line. In short, we are printing the entire matrix row by row.
2. How to Use Python For Loops for List Comprehension
If you’re creating a new list based on an existing list or other iterable, you can use list comprehension. It lets you create a new list by applying an expression to each item in an iterable, all in a single line of code.
The general syntax of list comprehensions is:
[expression for variable in iterable if condition]
Suppose you want to create a list of squares for a range of numbers, you can use the following list comprehension:
squares = [x ** 2 for x in range(1, 11)]
print(squares)
This code creates a list of squares for the numbers 1 to 10 using a single line of code.
3. How to Use the Enumerate() Function
When you’re looping through a list or string and you need to know the index of the current item, you use the enumerate() function. It returns each item along with its index, making it easier to handle the position of items.
The following is an example of enumerate function with a for loop:
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits):
print(f"{idx}: {fruit}")
In this code, we are looping through the fruits list, but we are also keeping track of the index of each item using the enumerate function, which returns each item in the list along with its index.
So, for each iteration of the loop, idx is the index and fruit is the item. Then, we print the index followed by the fruit. This gives us a numbered list of fruits.
Now that you’ve explored the advanced techniques in for loops, you can start to see how flexible loops can be in handling different scenarios. But, as with any tool, it’s essential to know when to use it and when another tool might be better suited.
With this in mind, let’s shift our focus to comparing for loops with while loops. This will help you decide which type of loop is the best fit for your specific coding situation.
For Loop vs While Loop
In Python, for and while loops serve different purposes.
For loops are used to iterate over sequences, like lists or tuples, and they have a definite iteration range.
While loops, on the other hand, continue running as long as a certain condition remains true.
# For loop example
for item in sequence:
# Code to execute for each item in sequence
# While loop example
while condition:
# Code to execute while condition is true
Suppose you want to print the first 5 numbers starting from 0.
Using a for loop, you’d write:
for i in range(5):
print(i)
The for loop is straightforward when you know the exact number of iterations beforehand, like in this case where you know you want to print 5 numbers.
On the other hand, using a while loop, you’d write:
i = 0
while i < 5:
print(i)
i += 1
In the while loop, you start with an initial condition (i < 5). The loop keeps running until the condition is no longer true. You must increment i in the body of the loop, or it would run forever.
The for loop is simpler and less error-prone for this task. But the while loop offers more flexibility for situations where the number of iterations is not known in advance.
For instance, consider a scenario where you’re prompting the user for input until they enter a valid number. You don’t know how many times you’ll have to ask, so a while loop is appropriate in this case:
while True:
user_input = input("Please enter a number: ")
if user_input.isdigit():
print("Thank you!")
break
else:
print("Invalid input. Try again.")
In this code, the while loop continues to prompt the user for input until they enter a valid number. The isdigit() function checks if the input is a number.
If it is, a message is printed and the loop is exited using the break statement. If it’s not a number, an error message is printed and the loop continues.
Final Thoughts
For loops are an essential tool in your programming toolbox. They provide a way to perform repetitive tasks efficiently. By understanding for loops, you gain the ability to manipulate data, automate tasks, and solve complex problems with just a few lines of code.
By mastering for loops, you can make your code more readable, more effective, and more Pythonic. Practice is the key to becoming comfortable with this construct. With the knowledge acquired from this guide, you are well-equipped to tackle a wide array of programming challenges using Python for loops!