0

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!

MThiele
  • 40
  • 3
  • As for your second example, if the `e.isoweekday() == 6:` is `True` then your `elif` for Sunday will never fire. So it's not surprising you never see that print out `Sunday!`. Change that `elif` to an `if` and rerun. – JNevill Jul 22 '22 at 17:40

1 Answers1

0

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]
Mark Reed
  • 91,912
  • 16
  • 138
  • 175