Is there a way to pop an element from a list with a default value if the index does not exist? I know that for dictionaries, python allows the pop function to return a default value as shown:
d = {"stack": "overflow"}
d.pop("stack", 10) # returns "overflow"
d.pop("badkey", 10) # returns 10
Is there an equivalent for lists? It seems python's default list pop method does not support default values so what is the most pythonic way to implement the functionality shown in the code snippet below?
def pop_default(input_list, index, default_value):
try:
temp = input_list[index].copy()
del input_list[index]
except IndexError:
return default_value
I would go with the one liner:
out = a.pop(a.index(value)) if value in a else default
where a is your list.
if you are given an index, then
out = a.pop(index) if index >=(len(a)-1) else default
EDIT:
After @Andrew's observation to account for negative index, the one-liner version would result as:
out = a.pop(index) if -len(a) <= index <= len(a)-1 else default
What's with the copy and del? just try to pop, and catch the IndexError:
def pop_default(input_list, index, default_value):
try:
return input_list.pop(index)
except IndexError:
return default_value
If are going to do that a lot of times in your codebase you can use a subclass (however it might be more confusing so it might be better to just use the above function)
from collections import UserList
class MyList(UserList):
def pop(self, index, default_value=None):
try:
return super().pop(index)
except IndexError:
return default_value
my_list = MyList(['a'])
print(my_list.pop(0))
print(my_list.pop(0, 'default'))
Outputs
'a'
'default'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With