On Tue, 20 Jun 2023 at 02:37, Peter Bona via Python-list <python-list@python.org> wrote: > > Hi > > I am wondering if there has been any discussion why NoneType is not iterable > My feeling is that it should be. > Sometimes I am using API calls which return None. > If there is a return value (which is iterable) I am using a for loop to > iterate. > > Now I am getting 'TypeError: 'NoneType' object is not iterable'. > > (Examples are taken from here > https://rollbar.com/blog/python-typeerror-nonetype-object-is-not-iterable/) > Example 1: > mylist = None > for x in mylist: > print(x) <== will raise TypeError: 'NoneType' object is not iterable > Solution: extra If statement > if mylist is not None: > for x in mylist: > print(x) > > > I think Python should handle this case gracefully: if a code would iterate > over None: it should not run any step. but proceed the next statement. > > Has this been discussed or proposed? >
Try this instead: for x in mylist or (): Now a None list will skip iteration entirely, allowing you to get the effect you want :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list