loop variable python code example
Example 1: python return iteration number of for loop
for iteration, item in enumerate(iteratable_object):
print(iteration)
[iteration for iteration, item in enumerate(iteratable_object)]
your_list = ["a", "b", "c", "d"]
for iteration,item in enumerate(your_list):
(iteration, item)
--> (0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
[iteration for iteration, item in enumerate(your_list)]
--> [0, 1, 2, 3]
Example 2: python for loop iterator
import numpy as np
arr = np.array([1,2,3,4,5,6,7,8,9])
for i in range(len(arr)):
if arr[i] % 2 == 0: arr[i] = 0
print(arr)