Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python's list.remove(value) determine what value to remove?

If I have list of objects:

l = [a, b, c]

Then I remove one of those objects:

l.remove(a)

How is python determining which item in the list to remove (under the hood)?

Is it using the memory location of a? (which you can view with hex(id(a)))

like image 893
zzz Avatar asked Dec 20 '13 01:12

zzz


1 Answers

  1. It iterates through the list, compares every item with the item to be removed and if it finds a match, it just removes that. It works in O(N). Source: https://wiki.python.org/moin/TimeComplexity

  2. It removes only the first matched item and returns immediately.

  3. If the item to be removed is not there, it fails with ValueError

This is the listremove function which removes the item from a list and it uses PyObject_RichCompareBool to check if the items are the same. And PyObject_RichCompareBool is implemented like this

/* Quick result when objects are the same.
   Guarantees that identity implies equality. */
if (v == w) {
    if (op == Py_EQ)
        return 1;
    else if (op == Py_NE)
        return 0;
}

res = PyObject_RichCompare(v, w, op);

If the identity of the objects are the same (if both the objects are the same), then return 1 otherwise compare the values and return the result.

like image 58
thefourtheye Avatar answered Oct 25 '22 12:10

thefourtheye