30

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?

1
  • What do you mean by "get the next entry in the loop"?
    – dlask
    Jul 4, 2015 at 3:01

5 Answers 5

29

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?
2
  • is it must to use 'else' after 'if'?
    – Karvy1
    Jul 4, 2015 at 3:18
  • 3
    nope! You don't need the else clause, you don't have to use it. Jul 4, 2015 at 3:20
15

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
>>> 
1
  • 1
    This is for the ones who need to have a one-liner: personally I'd rather have the if statement, because it's easier to read and understand. If you don't need to easily read and understand then go for it. Dec 6, 2021 at 23:30
10

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

1
  • Upvoting as this keep the thread-safe property of pop, and is EAFP
    – ofaurax
    Mar 5, 2021 at 9:46
4

Use this:

if exporterslist:
    importer = exporterslist.pop(0)
2
  • 3
    if exporterslist: will do the same job Jul 4, 2015 at 19:45
  • @pedjjj Thank you for your suggestion. Have included it.
    – Utsav T
    Dec 17, 2019 at 0:08
-3

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()
1
  • 5
    if len(exporterslist) > 0
    – rapt
    Feb 11, 2017 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.