The pointer to where the list really starts must be retained for the purpose of freeing the memory appropriately.

Indeed, remove(0) could be made faster by having a second pointer which is increased in this case. And if an .add(0, x) happens afterwards, this could be made faster by decrementing this "data start timer" as long as it is bigger than the "memory start timer".

But all other operations, i. e. insertions and deletions to other indexes, would still be O(n), so that wouldn't change much.

Just know what your operations will be and thus which data structure to pick.

Answer from glglgl on Stack Overflow
🌐
LabEx
labex.io › tutorials › python-what-is-the-time-complexity-of-list-append-and-remove-operations-in-python-397728
What is the time complexity of list append and remove operations in Python | LabEx
This means that the time it takes to remove an element from the list grows linearly with the size of the list. The reason for this time complexity is that the list.remove() operation needs to search for the first occurrence of the specified element in the list, and then remove it.
People also ask

What is the time complexity of .remove() in a Python list?
In Python, the .remove() method for lists has a time complexity of O(n), where 'n' is the number of elements in the list. This is because, after removing an element, all subsequent elements must be shifted to fill the gap. Therefore, the worst-case what is the time complexity of .remove() requires examining and potentially moving many elements.
🌐
scilift.blog
scilift.blog › time-complexity-remove
What is the Time Complexity of .remove()? - Scilift
Does .remove() on a set or dictionary also have O(n) time complexity?
No. For sets and dictionaries, .remove() or .discard() operations have an average time complexity of O(1). These data structures use hash tables, allowing for quick lookups and removals. Therefore, what is the time complexity of .remove() is much more efficient on sets and dictionaries.
🌐
scilift.blog
scilift.blog › time-complexity-remove
What is the Time Complexity of .remove()? - Scilift
How does .remove() perform on a large list versus a small list?
On a large list, you'll notice the O(n) time complexity of .remove() much more. The more elements in the list, the longer it takes to find and remove the desired value, since what is the time complexity of .remove() is directly proportional to the size 'n' of the list. Small lists will see quicker removal times because there are fewer elements to search through.
🌐
scilift.blog
scilift.blog › time-complexity-remove
What is the Time Complexity of .remove()? - Scilift
🌐
Reddit
reddit.com › r/learnpython › why is removing elements from a list so slow, and is there a faster way?
r/learnpython on Reddit: Why is removing elements from a list so slow, and is there a faster way?
April 21, 2024 -

I was trying to write a simple application, which is ao supposed to filter a list of words down to a list of words of a certain length. For that I could either remove the words of the wrong length, or create a new list of words with the correct length.

I had a list of around 58000 words, and wanted to filter out all the 6 letter words, which are around 6900.

with open('words.txt') as f:
    words = f.readlines()
    for i in range(len(words)):
        words[i] = words[i].strip()

length = int(input("Desired word length "))

for i in reversed(words):
    if len(i) != length:
        words.remove(i)

This took 22 seconds.

Another way is to just create a new list with words of the correct length. I did this as follows:

with open('words.txt') as f:
    words = f.readlines()
    for i in range(len(words)):
        words[i] = words[i].strip()

length = int(input("Desired word length "))
clw = []

for i in words:
    if len(i) == length:
        clw.append(i)

This only took 0.03 seconds. How can it be that creating a list of 6900 words takes 0.03 seconds, but removing 51100 words takes 22? It's only 7 times as many words, but takes 700 times as long. And is there a better and faster way to quickly remove list elements?

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-remove-rear-element-from-list
Python - Remove rear element from list - GeeksforGeeks
April 6, 2023 - # Python 3 code to demonstrate ... list is : [1, 4, 3, 6] Time complexity: O(1) - The pop() method takes constant time to remove the last element from the list....
Top answer
1 of 3
30

The cost of a remove is O(n) as you have to shuffle the elements to the "right" of that point "left" by one:

                 Delete D
                     |
                     V
+-----+-----+-----+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |  E  |  F  |  G  |
+-----+-----+-----+-----+-----+-----+-----+
                     <------------------
                      Move E, F, G left

If your test code is giving you O(1) then I suspect you're not measuring it properly :-)

The OpenJDK source, for example, has this:

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

and the System.arraycopy is the O(n) cost for this function.


In addition, I'm not sure you've thought this through very well:

for (int i = 0; i < list.size() ; i++)
    list.remove(i);

This is going to remove the following elements from the original list:

    0, 2, 4, 8

and so on, because the act of removing element 0 shifts all other elements left - the item that was originally at offset 1 will be at offset 0 when you've deleted the original offset 0, and you then move on to delete offset 1.

2 of 3
16

First off, you are not measuring complexity in this code. What you are doing is measuring (or attempting to measure) performance. When you graph the numbers (assuming that they are correctly measured) you get a performance curve for a particular use-case over a finite range of values for your scaling variable.

That is not the same as a computational complexity measure; i.e. big O, or related Bachman-Landau notations. These are about mathematical limits as the scaling variable tends to infinity.

And this is not just a nitpick. It is quite easy to construct examples1 where performance characteristics change markedly as N gets very large.

What are doing when you graph performance over a range of values and fit a curve is to estimate the complexity.

1 - And a real example is the average complexity of various HashMap functions which switch from O(1) to O(N) (with a very small C) when N reaches 2^31. The modality is because the hash array cannot grow beyond 2^31 slots.


The second point is that that the complexity of ArrayList.remove(index) is sensitive to the value of index as well as the list length.

  • The "advertised" complexity of O(N) for the average and worst cases.

  • In the best case, the complexity is actually O(1). Really!

    This happens when you remove the last element of the list; i.e. index == list.size() - 1. That can be performed with zero copying; look at the code that @paxdiablo included in his Answer.


Now to your Question. There are a number of reasons why your code could give incorrect measurements. For example:

  • You are not taking account of JIT compilation overheads and other JVM warmup effects.

  • I can see places where the JIT compiler could potentially optimize away entire loops.

  • The way you are measuring the time is strange. Try treating this as algebra.

            ((midPoint - start) - (stop - midPoint)) / count;
    

    Now simplify ... and the midPoint term cancels out.

  • You are only removing half of the elements from the list, so you only measuring over the range 50,000 to 100,000 of your scaling variable. (And I expect you are then plotting against the scaling variable; i.e. you are plotting f(N + 5000) against N.

  • The time intervals you are measuring could be too small for the clock resolution on your machine. (Read the javadocs for nanoTime() to see what resolution it guarantees.)

I recommend that people wanting to avoid mistakes like the above should read:

  • How do I write a correct micro-benchmark in Java?
🌐
Reddit
reddit.com › r/cpp_questions › is std::list::remove() o(n) and std::list::erase() o(1) time complexity
Is std::list::remove() O(n) and std::list::erase() O(1) time complexity : r/cpp_questions
August 27, 2021 - As far as your other questions about lists, you are correct and can check the reference for each of those operations and complexity times. For details, list is double-linked, so with erase, you provide the iterator (which is often just wrapping a pointer), so the node can be removed in O(1) time.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 617235 › java › remove-operation-LinkedList-time-complexity
How the remove operation in LinkedList is of O(1) time complexity? (Java in General forum at Coderanch)
Just to add to the other good ... that goes through elements using an Iterator and then removes them using its method, each removal will work in O(1) time, for the reasons Paul already explained (removal of a Node is an O(1) operation)....
🌐
Scilift
scilift.blog › time-complexity-remove
What is the Time Complexity of .remove()? - Scilift
In Python programming, the list.remove() method is a fundamental operation for data manipulation, and understanding its efficiency is crucial for optimizing code, especially when dealing with large datasets similar to those processed in big data environments. The O(n) time complexity, where n represents the number of elements in the list, characterizes the performance of list.remove(), indicating that, in the worst-case scenario, the operation's execution time increases linearly with the size of the list.
🌐
Scaler
scaler.com › home › topics › remove() in java
remove() in Java - Scaler Topics
April 7, 2024 - Since character A is present inside the list, the remove method will remove the character and return true. But what if we pass a character not present in the ArrayList? The remove method simply returns false in this case. The time complexity of the remove(int index) Method is O(N).
🌐
Medium
medium.com › @thakurinbox › time-complexity-of-popping-elements-from-list-in-python-215ad3d9c048
Time complexity of popping elements from list in Python! | by Naresh Thakur | Medium
December 13, 2021 - Consider we have following list. ... By doing a.pop() with no arguments it will remove and return the last element which has O(1) time complexity.
🌐
Finxter
blog.finxter.com › home › learn python blog › what is the difference between remove(), pop() and del in lists in python?
What is The Difference Between remove(), pop() and del in Lists in Python? - Be on the Right Side of Change
December 17, 2021 - li = [3, 5, 7, 2, 6, 4, 8, 2] li.remove(82) print(li) # ValueError: list.remove(x): x not in list · Complexity Analysis: The computational complexity when removing an element x from the list of n elements using the remove() method is O(n).
🌐
Quora
quora.com › Why-does-Javas-LinkedList-take-O-n-time-for-its-remove-method
Why does Java's LinkedList take O(n) time for its remove method? - Quora
Answer (1 of 5): The Object parameter in LinkedList’s “remove(Object o)” method is not the linked list’s node but an object that is stored inside a node. In addition to that object, the list node also has pointers/references to its previous and next nodes.
🌐
Quora
quora.com › What-is-the-time-complexity-of-removing-an-element-from-an-unsorted-linked-list
What is the time complexity of removing an element from an unsorted linked list? - Quora
Answer (1 of 2): The time complexity of removing an element from an unsorted linked list depends on which element the algorithm removes. If the algorithm is content to remove any element from the list, then the element at the head of the list could always be chosen. Removing the head element tak...
🌐
LinkedIn
linkedin.com › all › engineering › computer science
How can you remove an element from a Python list?
March 4, 2024 - Time complexity: O(n) due to list traversal. del list[index]: Directly deletes the element at the specified index without returning it. Time complexity: O(n) due to subsequent element shifting.
🌐
Medium
medium.com › @ivanmarkeyev › understanding-python-list-operations-a-big-o-complexity-guide-49be9c00afb4
Understanding Python List Operations: A Big O Complexity Guide | by Ivan Markeev | Medium
June 4, 2023 - When inserting or deleting an element at the beginning or middle of a Python list, the remaining elements must be shifted to accommodate the change. As a result, these operations have a linear time complexity of O(n).
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move). If you need to add/remove at both ends, consider using a collections.deque instead.
🌐
Baeldung
baeldung.com › home › java › java collections › time complexity of java collections
Time Complexity of Java Collections | Baeldung
September 24, 2025 - It iterates through the internal array and checks each element one by one, so the time complexity for this operation always requires O(n) time. contains() – implementation is based on indexOf(), so it’ll also run in O(n) time.
🌐
FavTutor
favtutor.com › blogs › python-set-remove
Python Set remove() Method Explained
September 18, 2024 - Now, coming to complexity. both the `remove()` and `discard()` methods have an average time complexity of O(1).