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

SparkAndShine picture SparkAndShine · Jul 23, 2015 · Viewed 13.9k times · Source

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?

Answer

loganasherjones picture loganasherjones · Jul 23, 2015

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.