Python for Loop: A Beginner’s Guide

Python for Loop: A Beginner’s Guide. In Python, for the loop is used to iterate over a sequence(Which could be a list, a tuple, a dictionary, a set, or a string) with the loop iterating over each element in the sequence. this makes for the loop particularly useful for performing a task repeatedly on each sequence element.

Syntax of the Loop in Python

The basic syntax of a for loop in Python looks like this.

Here, ‘element is the variable that takes the item’s value inside the sequence on each iteration, and ‘sequence’ is the collection you want to iterate over.

Basic Example of for Loop in Python

Let’s start with a simple example that prints each item in a list.

Basic Example of for Loop in Python

Iterating Through a Range

If you want to repeat an action a certain number of times with for loop, you can use the 'range()'function with a for loop.

Iterating Through a Range

The above Code will print numbers from 0 to 9. The range(10) function generates a sequence of numbers from 0 to 9.

Using Enumerate for Index and Value

Sometimes, you may need both the index and the value when looping through a sequence. This can be achieved by using the enumerate() function.

Using Enumerate for Index and Value

Looping through Dictionaries

While iterating into a dictionary, you can use the '.items()'method to retrieve both key and value.

Looping through Dictionaries

Nested for Loop in Python

A for loop can be nested inside another for loop to iterate over the item in a nested sequence.

Nested for Loop in Python

The for loop in Python is a powerful tool for iterating over items in a sequence or executing a block of code a certain number of times. Understanding how to use for loop will greatly enhance your ability to automate repetitive tasks in Python.

Happy Coding & Learning

See Also

Leave a Comment