Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function's iter count inside another function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading