Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pop from empty list

Tags:

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?

like image 399
Karvy1 Avatar asked Jul 04 '15 02:07

Karvy1


People also ask

Can you pop from a list in Python?

The Python language includes a built-in function that can be used to remove an element from a list: pop(). The pop() method removes an element from a specified position in a list and returns the deleted item.

What is the difference between pop () and pop 0 )?

pop([i]): Remove the item at the given position in the list, and return it. If no index is specified, a. pop() removes and returns the last item in the list.

Does pop remove element from list Python?

The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.


2 Answers

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? 
like image 156
NightShadeQueen Avatar answered Oct 11 '22 00:10

NightShadeQueen


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 >>>  
like image 30
Gergely M Avatar answered Oct 11 '22 01:10

Gergely M