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

get the next value returned by a for loop's generator expression

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:

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

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

>Solution :

one thing you can do is converting the list into an iterator object and use the iterator properties such as next() and slice().

for more details I found this answer from a previous post very complete:
https://stackoverflow.com/a/22296065/14395688

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