DEV Community

Max
Max

Posted on • Updated on

Python For Loops, Range, Enumerate Tutorial

Python for loop is used to iterate over a sequence of elements such as a list, tuple, or string. The range function can be used to create a sequence of numbers, and enumerate can be used to iterate over a sequence while also keeping track of the index.

Python for Loop

The syntax of the for loop in Python is as follows:

for variable in sequence:
    # code to be executed for each element in sequence
Enter fullscreen mode Exit fullscreen mode

Here, variable is a new variable that takes on the value of each element in the sequence. The code inside the loop is executed once for each element in the sequence.

Example

Let's say we have a list of names and we want to print each name:

names = ['One', 'Two', 'Three', 'Four']

for name in names:
    print(name)
Enter fullscreen mode Exit fullscreen mode

Output:

One
Two
Three
Four
Enter fullscreen mode Exit fullscreen mode

The range Function

The range function in Python is used to create a sequence of numbers. It can take up to three arguments: start, stop, and step. The start argument specifies the starting value of the sequence (default is 0), the stop argument specifies the ending value (not inclusive), and the step argument specifies the step size (default is 1).

Example

Let's say we want to print the numbers from 0 to 9:

for i in range(10):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
3
4
5
6
7
8
9
Enter fullscreen mode Exit fullscreen mode

The enumerate Function

The enumerate function in Python is used to iterate over a sequence while also keeping track of the index. It returns a tuple containing the index and the element at that index.

Example

Let's say we have a list of names and we want to print each name along with its index:

names = ['One', 'Two', 'Three', 'Four']

for i, name in enumerate(names):
    print(i, name)
Enter fullscreen mode Exit fullscreen mode

Output:

0 One
1 Two
2 Three
3 Four
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial
Python Lists tutorial
Python dictionaries comprehension tutorial

Top comments (0)