What is the best way to skip the "NoneType" variable?

The list contains several items NoneType. To skip 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?

+4
source share
3 answers

Generally, you should not use a template try: except:for a control flow if you can help it. There is some overhead associated with creating an exception that is not necessary in this context. Hope this helps.

+7
source

As people noted in the comment, the approach is trynot a good way, because you can skip the element due to any other exceptions that occur in this block.

, . , , None, :

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

P.S. , - list.

+3

The second will not be good, because it throws an exception whenever an element of type occurs None. The exception will be handled differently in python.

In your case, you give a pass, so that will be done.

Cleaner way:

clean = [x for x in lis if x != None]

or As stated in the comments, which you can also use, no, even if it is essentially compiled into the same bytecode:

clean = [x for x in lis if x is not None]

Hope this helps. When in Rome they do as the Romans :)

+1
source

Source: https://habr.com/ru/post/1599294/


All Articles