I am working on a program where I need to test each value in a list against a large number of conditions for which I am using a standard for item in list
loop. However, in some rare circumstances I need to read in three items to check the condition.
I know that this could be solved by using a while loop and indexing but my code uses a fair few continue
blocks and relies heavily on indexing so that seems like an excellent way to introduce hard-to-find bugs.
currently my solution is simply to have a skip_num
variable and have the first code within the for loop be:
if skip_num:
skip_num -= 1
continue
However, this is still pretty clunky and leaves a variable dangling out there which is able to screw with the reading of the conditions. Can anyone recommend a more elegant way of achieving the same thing? Ideally I would like to do something similar to what the next
function does for generator expressions but I know python for loops really hate you trying to mess with their control variable.
Thanks
Clarification: ideally the solution would work something like this:
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in array:
print(number)
if number == 5:
num = number
next_1 = next(array)
next_2 = next(array)
print(f"{num}, {next_1}, {next_2}")
# output
# 1
# 2
# 3
# 4
# 5 6 7
# 8
# 9