Home > OS >  How to remove Weekends from a datelist?
How to remove Weekends from a datelist?

Time:07-23

I am using the following code to remove weekends from a datelist:

def clear_weekends(date_list):
for i, e in enumerate(date_list):
    if e.isoweekday() == 7: 
        del date_list[i]
for i, e in enumerate(date_list):
    if e.isoweekday() == 6: 
        del date_list[i]
return date_list

For some reason though, it doesn't work and apparently random saturdays are not removed. Before, I had both saturday and sunday in the same for loop with the same if-statement. Then, it seemed not to delete any saturdays at all.

Does anybody know what is going on?

For a larger list, I can use

for e in clear_weekends(datelist):
if e.isoweekday() == 6: print("Saturday!")
elif e.isoweekday() == 7: print("Sunday!")

and I will still receive varying amount of saturdays (never sundays though).

Any help is appreciated!

CodePudding user response:

It's generally a bad idea to modify a list while you're iterating over it. You should delete them with a filter expression instead. Maybe a list comprehenseion?

def clear_weekends(date_list):
    return [d for d in date_list if d.isoweekday() < 6]
  • Related