Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pop from a Python list with default value

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
like image 845
Andrew Mascillaro Avatar asked Nov 08 '25 11:11

Andrew Mascillaro


2 Answers

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
like image 122
Martí Avatar answered Nov 09 '25 23:11

Martí


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'
like image 36
DeepSpace Avatar answered Nov 10 '25 00:11

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!