pythoniterationstopiteration

Iteration through a list


I'm very new to Python hence this question.

I have a list that represents dates i.e. Mondays in March and beginning of April

[2, 9, 16, 23, 30, 6]

The list, 'color_sack' is created from a scrape of our local council website.

Im using

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

todays_date.day returns just the number representing the day i.e. 30

This has worked well all month until today 30th when it now displays a error

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

Is it possible to step through the list a better way so as next_rubbish_day would populate the 6 after the 30 from the list above. I can see why its not working but can't work out a better way.

When April starts the list will be updated with the new dates for Mondays in April through to the beginning of May


Solution

  • Consider, if your current month is march and corresponding list of dates is [2, 9, 16, 23, 30, 6] and today's date is 30, basically what we are doing is :

    1. Checking if there is any date in color_sack that is greater than
      today's date if it is then we yield that date. In our case no date in the list is greater than 30.
    2. If the 1st condition fails we now find out the index of maximum date in the color_sack, in our case the max date is 30 and its index is 4, now we found out if there is a idx greater than the index of maximum date in the list, if it is then we return that date.

    This algorithm will comply with any dates in the current month eg March. As soon as the new month starts eg. "April starts the list will be updated with the new dates for Mondays in April through to the beginning of May". So this algorithm will always comply.

    Try this:

    def next_rubbish_day(color_sack, todays_date):
        for idx, day in enumerate(color_sack):
            if day > todays_date or idx > color_sack.index(max(color_sack)):
                yield day
    

    print(next(next_rubbish_day(color_sack, 6)))
    print(next(next_rubbish_day(color_sack, 10)))
    print(next(next_rubbish_day(color_sack, 21)))
    print(next(next_rubbish_day(color_sack, 30)))
    print(next(next_rubbish_day(color_sack, 31)))
    

    OUTPUT:

    9
    16
    23
    6
    6