Python for-loop

Loops are the way of performing repetitive tasks efficiently.

For example, you need to add 10 to each of the values present in the list [ 10,20,30,40 ]. Hence we go through each of these values one by one and perform the addition, this is looping.

In the below code, a temporary variable ‘i’ is chosen as the iterator. the value of ‘i’ changes four times in the below code, as there are four values in the list, hence, in the first round the value of ‘i’ will be 10, in the next round it will be 20 so on and so forth.

instead of the variable name ‘i’, you can choose any other valid python variable name like my_iterator, list_iterator, myValue etc.

Sample Output:

Python Loops
Python Loops

Looping with multiple iterators

Python has a facility to loop multiple iterators simultaneously. The keyword to be used in zip.

Sample Output:

Iterating multiple objects simultaneuously  in Python
Iterating multiple objects simultaneuously in Python for loop

Nested for Looping

You can run a sub loop inside a loop as well. Here, each value of the outer loop object will be used once with each value of the inner loop object.

Sample Output:

Python nested loop
Python nested for loop

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

1 thought on “Python for-loop”

Leave a Reply!

Your email address will not be published. Required fields are marked *