Loop over empty iterator does not raise exception

前端 未结 3 1433
囚心锁ツ
囚心锁ツ 2020-12-12 05:00

I am on Python 3.6.7.

I just noticed that a for loop over an empty list does not loop even once. After some thought, that made some sense to me. I.e.

3条回答
  •  臣服心动
    2020-12-12 05:34

    Why do you need to do something if the loop wont run because the list is empty? It's perfectly normal behavior. If you expect for some reason to have at least one item (maybe having no items in array is a measure of error in your program) then check if len(iterator) == 0 as you suggested earlier. Its a perfectly valid way to do it.

    By the way exeptions are the way to go in those cases when you are checking the values of variables etc. Asserts are more of the hard-coded info for critical failures and SHOULD NOT be used for reporting usual errors as they cant be handled.

提交回复
热议问题