A list contains several NoneType
elements. To skip the NoneType
,
for item in list :
if item is not None :
fp.write(item + '\n')
#OR
for item in list :
try :
fp.write(item + '\n')
except :
pass
Which one is better and why?
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 .
The TypeError: 'NoneType' object is not iterable error is raised when you try to iterate over an object whose value is equal to None. To solve this error, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list.
The Python "AttributeError: 'NoneType' object has no attribute 'get'" occurs when we try to call the get() method on a None value, e.g. assignment from function that doesn't return anything. To solve the error, make sure to only call get() on dict objects.
Use the is operator to compare to None in Python, e.g. if my_var is None: . The is operator returns True if the two values point to the same object (it checks for identity), whereas the double equals == operator checks if the two values are equal. Copied!
The second won't be good as it will throw an exception whenever a None
type element is encountered. Exception will handled in it's own way in python .
In your case you are giving a pass , so that will be done .
A more cleanest way would be :
clean = [x for x in lis if x != None]
or As pointed in the comments you could also use is not, even if it essentially compiles to the same bytecode:
clean = [x for x in lis if x is not None]
Hope this helps . When in rome do like Romans :)
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