To check whether a variable is None or not, use the is operator in Python. With the is operator, use the syntax object is None to return True if the object has the type NoneType and False otherwise.
One way to avoid this error is to check before iterating on an object if that object is None or not. In addition, another way to handle this error: Python nonetype object is not iterable is to write the for loop in try-except block. Thirdly, it is to explicitly assign an empty list to the variable if it is None .
Just use type(None) . If type(None) shows NoneType for you, rather than something like <class 'NoneType'> , you're probably on some nonstandard interpreter setup, such as IPython. It'd usually show up as something like <class 'NoneType'> , making it clearer that you can't just type NoneType and get the type.
I'm trying to check whether an object has a None type before checking it's length. For this, I've done an if statement with an or operator:
if (cts is None) | (len(cts) == 0):
return
As far as I can tell, the object cts
will be checked if it's None, and if it is, the length check won't run. However, the following error happens if cts
is None:
TypeError: object of type 'NoneType' has no len()
Does python check both expressions in an if statement, even if the first is true?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With