How to loop in Python

Python Lists

Python has some pretty powerful functionality to loop through any kind of Python list. The syntax to do so is simple:

for i in list:
    # do something

For example, consider the following:

anything = randint(0,100)
python_list = ['can', 'contain', anything, ['even', 'other', 'lists']]
for i in python_list:
print(i)

Conventionally, in languages like C++ and Java, a variable is arithmetically changed upon every iteration of the loop. For example, in the following for loop, the variable i is incremented upon each iteration:

for(int i = 0; i < arr_length; i++)
{
    cout << i << endl;
}

In Python, however, a variable is set to an element in a given list upon every iteration.

C++ for loops
C++ for loops
Python for loops
Python for loops

The range() function

To achieve the functionality of conventional for-loop in Python, the range() function is used. It returns a list of integers. It works like so:

>> range(start,end)
>> [start, start+1, start+2..., end-1]
start = 0
end = 10
for i in range(start,end):
print(i)

It can also be done in increments/decrements like so:

# Increments
for i in range(0,10,2):
print(i)
# Decrements
for i in range(10,0,-2):
print(i)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved