I want to count a function’s iteration inside a for loop, which is also a function.
def a():
return list(['a', 'b'])
def b():
count = 0
for i in range(5):
print(i)
count += 1
for i in a():
b()
This is what I get:
0 1 2 3 4 0 1 2 3 4
This is what I want :
0 1 2 3 4 5 6 7 8 9
>Solution :
The problem with this code is that when each time you iterate through the list your defined function a returns, it prints out the same numbers in the b function for each iteration of your a list. Something like this would work:
def a():
return list(['a', 'b'])
numbers = []
count = -1
def b():
global count
for i in range(5):
count += 1
numbers.append(count)
return count
for i in a():
b()
print(numbers)
What this does is define a numbers list to hold the number of each iteration. Then, a count that starts at -1 (since the b function will add one each iteration through your range, this will make the first number added to the numbers list 0). Each time it iterates through b, it adds to the counter which is then appended to the numbers list.