Iterate a list without next()

Viewed 79

I have a list called current_month_list which is populated each month with Mondays in the month. ie for June it would be:

current_month_list = 6, 13, 20, 27

Im using

next_rubbish_day = next(x for x in current_month_list if x > todays_date.day)

to return the next Monday in the list i.e. 20 as todays the 16

This has worked well but im trying to convert over to Pyscript it use this in a different environment and apparently (quoted on another site) '

pyscript includes an async python interpreter and doesn't implement certain features that are particularly difficult in an interpreter. That includes generators.

The error im getting is

not implemented ast ast_generatorexp

So my question is, is there another way to code this. Im not to good with python so would appreciate some help. Thank you in anticipation.

2 Answers

Probably do something like this (you'll have to set or import the todays_date.day). There are bunch of ways to do this with for, while, break, return, etc. Really just depends on what you want! Good luck!

def main():
    print(date_fun())
    
def date_fun():    
    current_month_list = [6, 13, 20, 27]
    for y in current_month_list:
        if y > todays_date.day:
            return y

main()

Since generators are forbidden, just fall back to a regular loop. next() will return the next item in that generator expression, and since you just created the generator, that will be the first item. So just break out of your loop once you have your first item:

for x in current_month_list:
    if x > todays_date.day: 
        next_rubbish_day = x
        break 

Now, this code will not throw any errors if none of x > todays_date.day in current_month_list; your original code would throw a StopIteration exception. To implement this functionality, all you need is to use the for..else form:

for x in current_month_list:
    if x > todays_date.day: 
        next_rubbish_day = x
        break 
else:
    # This code runs only if the loop finishes without being broken
    raise StopIteration()

This snippet behaves identically as far as I know to your next(...) statement.

Related