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

17,987

Solution 1

As a general rule of thumb, you should not really be using the try: except: pattern for control flow if you can help it. There is some overhead involved with raising an exception that is unnecessary in this context. Hope this helps.

Solution 2

As people mentioned in the comment the try approach is not the good way, because you might skip an element because of any other exceptions that rise in that block.

So the first option is better. Here is an alternative, where you can be sure that all elements are not None, but it will consume more memory:

for item in (element for element in list if element is not None):
    fp.write(item + '\n')

P.S. do not use built-in names as variable names, in your case - list.

Solution 3

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

Share:
17,987
SparkAndShine
Author by

SparkAndShine

For more about me, please refer to, Blog: sparkandshine.net GitHub: https://github.com/sparkandshine WeChat: SparkAndShine

Updated on June 04, 2022

Comments

  • SparkAndShine
    SparkAndShine almost 2 years

    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?