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.
range()
functionTo 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 = 0end = 10for i in range(start,end):print(i)
It can also be done in increments/decrements like so:
# Incrementsfor i in range(0,10,2):print(i)# Decrementsfor i in range(10,0,-2):print(i)
Free Resources