How To Start A For Loop In Python

For loops are fundamental programming constructs that enable developers to create iteration in their code while automating repetitive tasks effectively. Python offers a clean and straightforward syntax to implement for loops, making your code more readable. In this tutorial, we’ll discuss how to start a for loop in Python, including relevant concepts like the range function and list comprehensions.

Step 1: Basic Syntax of For Loop

The general syntax for a for loop in Python is:

Here, the iterable can be a list, tuple, string, dictionary, or range object. The variable stores the current element in the iterable, and the loop iterates through to the next element until it reaches the end of the iterable.

Step 2: Looping Through Lists

To illustrate the use of a for loop, we’ll create a list and iterate through each item:

The output of the above code will be:

apple
banana
cherry

Step 3: Using the Range Function in For Loop

In some instances, you might need to iterate over a range of numbers rather than a collection of items. You can use Python’s range() function to generate a range object that is suitable for iterations. The range function takes three arguments: start, stop, and step – where start is inclusive, and stop is exclusive.

Let’s iterate through the numbers from 1 to 10 using the range function:

The output of the above code will be:

1
2
3
4
5
6
7
8
9
10

Step 4: Looping Through Strings

You can also iterate through each character of a string using a for loop:

The output of the above code will be:

p
y
t
h
o
n

Step 5: List Comprehensions

Python’s list comprehensions offer a concise way to create new lists by iterating through an iterable and applying specific conditions or actions to each element. The general syntax for list comprehension is:

Suppose we want to create a list containing the squares of all even numbers from 1 to 10. Using list comprehension, we can achieve that in a single line:

The output of the above code will be:

[4, 16, 36, 64, 100]

Full Code

Here is the full code used in this tutorial:

Conclusion

Now you have a solid understanding of how to start a for loop in Python, including iterating through various types of iterables and using the range function. With this knowledge, you’re well-equipped to write more efficient, concise, and readable code for your future projects.