Python: pop from empty list

I am using below line in a loop in my code

importer = exporterslist.pop(0)

      

If the exporter list has no entries or this null

, it returns error: IndexError: pop from empty list

. How can I bypass the exporter list without entries in it?

One idea I can think of is if the exporter list is nonzero then importer = exporterslist.pop(0)

otherwise get the next entry in the loop. If the idea is correct, how do I code it in python?

+8


source to share


5 answers


You are on the right track.



if exporterslist: #if empty_list will evaluate as false.
    importer = exporterslist.pop(0)
else:
    #Get next entry? Do something else?

      

+12


source


You can also use try / except function

try:
    importer = exporterslist.pop(0)
except IndexError as e:
    print(e)

      



If you're always popping off the front, you might find deque a better option, as deque.popleft () is 0(1)

.

+4


source


This...

exporterslist.pop(0) if exporterslist else False

.. is somewhat the same as @nightshadequeen's accepted answer just shorter:

>>> exporterslist = []   
>>> exporterslist.pop(0) if exporterslist else False   
False

      

or maybe you can use this to get no return:

exporterslist.pop(0) if exporterslist else None

>>> exporterslist = [] 
>>> exporterslist.pop(0) if exporterslist else None
>>> 

      

+4


source


Use this:

if len(exporterslist) != 0:
    importer = exporterslist.pop(0)

      

+1


source


You can also .pop () only if there are elements in the list that determine if the length of the list is 1 or more:

if len(exporterslist) > 1:
    importer = exporterslist.pop()

      

0


source







All Articles