Search code examples
pythonlistperformanceoptimization

remove element by value in list Python fastest


what is the fastest way to remove an element from a list by its value?

I believe list.remove("element_to_be_removed") is the naive way. How can we optimize it?


Solution

  • Finding an element in a list by value is O(n), as is removing it once you have found it. There is no way to reduce this; it's inherent in how lists are built.

    Finding and/or removing an element in a set is O(1).

    Converting a list into a set is O(n). If you have a list and you need to remove one item, converting it to a set and then removing one item doesn't get you to O(1), because the set conversion itself is an O(n) operation. You're better off using list.remove().

    If you have a list of unique items, and you anticipate needing to remove many items from it in an unordered way (say, you're going to eventually remove each item one by one), you can change that from an O(n^2) operation to an O(n) operation by converting the entire list into a set (once, in O(n)) and then removing the elements one by one after that (in O(1) per item, hence O(n) overall).

    The ideal solution (if possible) is to anticipate the ways in which you'll need to use this collection of items and make it a set from the beginning if the functionality of a set is a better fit for what you're doing.