Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way is better to skip the 'NoneType' variable?

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?

like image 331
SparkAndShine Avatar asked Jul 23 '15 12:07

SparkAndShine


People also ask

How do you avoid NoneType objects in Python?

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 .

How do you handle NoneType errors?

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.

How can we avoid NoneType object has no attribute?

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.

How do you compare NoneType?

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!


1 Answers

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 :)

like image 93
coder3521 Avatar answered Oct 27 '22 13:10

coder3521