As one of the most basic functions in programming, loops are an important piece to nearly every programming language. Loops enable developers to set certain portions of their code to repeat through several loops, referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.

For loops

for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.

for i in [0, 1, 2, 3, 4]:
 print(i)

The above for loop iterates over a list of numbers.

Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output will be as follow:

0
1
2
3
4

Range Function in for Loops

The range is a function that returns a series of numbers under an iterable form. Thus it can be used in for loops:

for i in range(5):
 print(i)
0 
1 
2 
3 
4

Gives the same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.

#by aman kharwal #python #data science

Loops in Python | Data Science | Machine Learning | Python
1.25 GEEK