How to Use for loops in Python with example

Have you ever wanted to write code that is faster and shorter? Well, the amazing for loop in Python can help you do just that! In this guide, we’ll explain the incredible capacities of for loops and how they can be used in many different ways.

What are For Loops?

For loops are like a helpful assistant in programming. They allow you to repeat a set of instructions for each item in a list or sequence. It’s a way to automate repetitive tasks and make your code more efficient.

Instead of writing the same code over and over, you can use a for loop to go through each item and perform actions on them.

It allows you to iterate over a sequence of elements, such as lists, strings, or ranges, and perform operations on each element in a systematic manner.

How for loops works

for loop consists of three important parts: the loop variable, the iterable, and the indented block of code.

The loop variable is like a temporary name that represents each item in a collection. It changes its value for each iteration of the loop. You can choose any name you want for the loop variable, but it’s best to pick a name that describes what the loop is doing.

The iterable is the collection of items that the loop variable goes through. It can be a list of names, a string of characters, or even a range of numbers. It’s like a group of things you want to work with in the loop.

The indented block of code is where you write the instructions that you want to perform on each item in the iterable. This block of code is executed once for every item in the iterable. It allows you to automate repetitive tasks easily, as the loop takes care of going through each item and applying the instructions.

How to Access Index in Python for Loop

In Python, you can access the index of an element while using a for loop by using the enumerate() function. Here’s an example to help you understand:

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

In the above code, we have a list of fruits. The enumerate() function is used to iterate over the list and provide both the index and the corresponding element. Inside the for loop, we have two variables: index and fruit. index represents the index of the current fruit, while fruit represents the actual fruit element.

0 apple
1 banana
2 orange

Example 1: Printing Numbers

Suppose you want to print the numbers from 1 to 5. Instead of writing five separate print statements, you can achieve the same result with a concise for loop.

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

In this example, the range(1, 6) function generates a sequence of numbers starting from 1 up to, but not including, 6. The loop iterates over each number in this sequence, and the print(number) statement displays each number on a new line. By using a for loop, you can easily print the desired numbers without repetitive code.

Example 2: Iterating over a List

Let’s say you have a list of names and you want to greet each person individually. A for loop can simplify this task.

names = ["Aman", "Nitin", "Nikunj", "Sainath"]

for name in names:
    print("Hello, " + name + "!")

Output:

In this example, the for loop iterates over each name in the names list. The print("Hello, " + name + "!") statement greets each person by concatenating their name with a greeting message. By using a for loop, you can easily apply the greeting to each name in the list.

Hello, Aman!
Hello, Nitin!
Hello, Nikunj!
Hello, Sainath!

Example 3: Calculating the Sum of Numbers

Suppose you have a list of numbers and you want to calculate their sum. A for loop can help you accomplish this task efficiently.

numbers = [1, 2, 3, 4, 5, 7, 8, 9]
sum = 0

for num in numbers:
    sum += num

print("The sum is:", sum)

Output:

In this example, the for loop iterates over each number in the numbers list. The sum += num statement adds each number to the sum variable. Finally, the sum is displayed using the print statement. By utilizing a for loop, you can easily calculate the sum of a list of numbers without manually adding them one by one.

The sum is: 39

Example 4: for loops with Range

The range function is a powerful tool in Python that generates a sequence of numbers. By combining range with for loops, you can simplify complex tasks, including iterating a specific number of times.

for i in range(9):
    print("Number", i+1)

In this example, the range(9) function generates a sequence of numbers from 0 to 8. The for loop iterates over each number in this sequence, assigning it to the loop variable i. The print("Nummber", i+1) statement displays the current iteration number.

Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9

Example 5: Customizing Range Start, Stop, and Step

The range function can be customized to start from a specific value, end at a different value, and even define the step size for each iteration.

for num in range(2, 21, 2):
    print(num)

Output:

In this example, the range(2, 21, 2) function generates a sequence of even numbers starting from 2 and ending before 21. The 2 in the range function represents the start value, 21 is the stop value (exclusive), and 2 is the step size.

The for loop iterates over each number in this sequence, and the print(num) statement displays each even number. By customizing the parameters of the range function, you can easily iterate over a specific range of values with a defined step size.

2
4
6
8
10
12
14
16
18
20

Example 6: A pattern generated using a for loop in Python

rows = 5

for i in range(1, rows+1):
    for j in range(1, i+1):
        print(j, end=" ")
    print()

Output:

In this pattern, the outer for loop controls the number of rows, while the inner for loop generates the numbers to be printed in each row.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Tips and Best Practices for Loops in Python

1. Choose clear and meaningful variable names

When using for loops, it’s important to select variable names that describe what the loop is doing. Instead of using vague names like “i” or “x”, opt for names that make it easy to understand the purpose of the loop. For example, if you’re looping through a list of names, use a variable name like “name” to make your code more readable.

2. Use list comprehensions for concise solutions

List comprehensions are a powerful and compact way to create lists or perform operations within a for loop. They allow you to combine the loop and conditional statements into a single line of code, making it shorter and more elegant. It’s a handy technique to learn, as it can make your code more efficient and easier to understand.

3. Be mindful of common mistakes and errors

There are a few common mistakes to watch out for when working with for loops. These include:

  • Modifying the list you’re looping through: It’s best to avoid changing the list while looping through it, as it can lead to unexpected results or errors. If you need to modify the list, consider creating a separate copy to work with.
  • Avoiding infinite loops: Make sure your loop has a clear termination condition, so it doesn’t run forever. Double-check that your loop condition will eventually become false.
  • Pay attention to indentation: Python relies on proper indentation to define the scope of the loop. Make sure your code is correctly indented to avoid syntax errors.

1 thought on “How to Use for loops in Python with example”

Leave a Comment