Introduction

Let’s say that we have a list. We want to iterate over this list, printing out the index followed by the list element or value at that index. Let’s accomplish this using a for loop:

num_list= [42, 56, 39, 59, 99]

for i in range(len(num_list)): 
    print(i, num_list[i])
## output: 
0 42
1 56
2 39
3 59
4 99

range() is a built-in function in python that allows us to iterate through a sequence of numbers. As seen above, we use the for loop in order to loop through a range object (which is a type of iterable), up to the length of our list. In other words, we start at an i value of 0, and go up to (but not including) the length of num_list, which is 5. We then access the elements of _num_list _at the _i-th _index using square brackets.

However, it is important to understand that we are not actually iterating over num_list. In other words, i serves as a proxy for the index that we can use to access the elements from num_list.

#data-science #python #software-engineering #programming #technology

Looping  in Python
1.10 GEEK