简体   繁体   中英

How to remove and return element in python list

In python you can do list.pop(i) which removes and returns the element in index i, but is there a built in function like list.remove(e) where it removes and returns the first element equal to e?

Thanks

I mean, there is list.remove , yes.

>>> x = [1,2,3]
>>> x.remove(1)
>>> x
[2, 3]

I don't know why you need it to return the removed element, though. You've already passed it to list.remove , so you know what it is... I guess if you've overloaded __eq__ on the objects in the list so that it doesn't actually correspond to some reasonable notion of equality, you could have problems. But don't do that, because that would be terrible.

If you have done that terrible thing, it's not difficult to roll your own function that does this:

def remove_and_return(lst, item):
    return lst.pop(lst.index(item))

Is there a builtin? No. Probably because if you already know the element you want to remove, then why bother returning it? 1

The best you can do is get the index, and then pop it. Ultimately, this isn't such a big deal -- Chaining 2 O(n) algorithms is still O(n), so you still scale roughly the same ...

def extract(lst, item):
    idx = lst.index(item)
    return lst.pop(idx)

1 Sure, there are pathological cases where the item returned might not be the item you already know... but they aren't important enough to warrant a new method which takes only 3 lines to write yourself :-)

Strictly speaking, you would need something like:

def remove(lst, e):
    i = lst.index(e)
    # error if e not in lst
    a = lst[i]
    lst.pop(i)
    return a

Which would make sense only if e == a is true, but e is a is false, and you really need a instead of e .

In most case, though, I would say that this suggest something suspicious in your code.

A short version would be :

a = lst.pop(lst.index(e))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM