Python break loop with one line of code without using enumerate()

55 views Asked by At

If I want to add a break to my for or while loop at certain iteration can it be done without adding counter?

    i=1
    for line in zip(*input):
        print(format_row.format(*line))
        if i > 3: break
        i += 1

also without enumerate():

    for i, line in enumerate(zip(*input)):
        print(format_row.format(*line))
        if i > 3: break
        

EDIT:

Please solution without including additional libraries.

I don't want to use enumerate because i have to edit code in for statement too much, its a temporary break for example to print N number of lines rather than 1000 lines, so debugging can be fast. I want to add quick break and then remove it without need to modify original code of for loop.

I want to add 2 lines maximum one outside the for loop another inside the for loop, how to make this work, function will be stored elsewhere and reused many times so its not a problem, function can be as long as required.

    # function does not count as extra code because it is reusable
    def check(num):
        if num > 3:
            return True
        else:
            num += i


    # line 1
    i = 1

    for line in zip(*input):
        print(format_row.format(*line))
        
        # line 2
        if check(i): break
1

There are 1 answers

1
Brendon Mendicino On

You could add a range() zipped to your iterator, thus limiting your loop without the addition of lines or break statements.

# range limits the loop
for line, _ in zip(zip(*input), range(3)):
    print(format_row.format(*line))