Home > Software engineering >  Print x Elements from a list in a for loop
Print x Elements from a list in a for loop

Time:04-10

I am trying to output only 3 elements from the list to the console at once, when user clicks enter I want to display 3 more until the end of the list but every time the loop enters the else clause I lose one element. I checked if the list was correct and it was, it had all the elements in it. How can I fix this?

def print_logs(self, logs: dict):
    display_count = 0
    for key, val in logs.items():
        for entry in val:
            if display_count < int(self.configuration["num_lines"]):
                print(entry)
                display_count  = 1
            else:
                input()
                display_count = 0

CodePudding user response:

You are not "losing" an element. When you enter the else statement, you are simply not doing anything with the current value of the iterator.

To fix your issue, I would suggest to do this:

def print_logs(self, logs: dict):
display_count = 0
for key, val in logs.items():
    for entry in val:
        print(entry)
        display_count  = 1
        if display_count == int(self.configuration["num_lines"]):
            input()
            display_count = 0
  • Related