Python: pop from empty list

I am using below line in a loop in my code

importer = exporterslist.pop(0)

If exporterslist has no entries it returns error: IndexError: pop from empty list. How can I bypass exporterslist with no entries in it?

One idea I can think of is if exporterslist is not None then importer = exporterslist.pop(0)
else get the next entry in the loop.
If the idea is correct, how to code it in python?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re on the right track.

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

Method 2

This one..

exporterslist.pop(0) if exporterslist else False

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

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

or maybe you could use this to get no return at all:

exporterslist.pop(0) if exporterslist else None

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

Method 3

You can also use a try/except

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

If you are always popping from the front you may find a deque a better option as deque.popleft() is 0(1).

Method 4

Use this:

if exporterslist:
    importer = exporterslist.pop(0)

Method 5

You can also .pop() only if the list has items in it by determining if the length of the list is 1 or more:

if len(exporterslist) >= 1: #if the length of the list is equal or higher than one
    importer = exporterslist.pop()


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x