From the docs:

list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.

Without going into the details of the implementation, the item to remove can be anywhere in the list. A linear scan time is necessary in order to find the item before it can be removed. Once you find the index of the item to remove, you need to shift all the elements down by one index. In any case there's index amount of traversal and size - index amount of shifting involved. Therefore the removal time is equivalent to traversing the entire list: O(n).

You can find the source here: https://hg.python.org/cpython/file/tip/Objects/listobject.c#l2197 (also look for list_ass_slice(..)).


However, a set is different. It uses the hash value of the object being stored to locate it in its buckets. On an average, locating of objects using hash value is almost constant time. Note that it might not always be constant time where there's hash collision and a further search is required. But assuming a good hash function, it usually is.

UPDATE: I must thank Stefan Pochmann for pointing out the mistake.

Answer from UltraInstinct on Stack Overflow
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ TimeComplexity
TimeComplexity - Python Wiki
The average case for an average value of k is popping the element the middle of the list, which takes O(n/2) = O(n) operations. [3] = For these operations, the worst case n is the maximum size the container ever achieved, rather than just the current size. For example, if N objects are added ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49732932 โ€บ python-list-del-insert-no-of-assignments-and-time-complexity
Python list - del, insert, no. of assignments and time complexity - Stack Overflow
I'm wondering about how many assignments python makes during an insert on an arbitrary index and how many assignments is being made when deleting the first element del(list[0]). I'm a little bit confused since the time complexity for these 2 operations are O(n), n being the number of elements in the list, but when thinking about it I get it to be O(n-1).
Discussions

algorithm - Why does Python take O(n) time to remove the first element from a list? - Stack Overflow
The Python wiki page on time complexity says that deleting an item takes O(n) time. The description of the deque class in the documentation of the collections module says that "list objects [...] i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Why is removing elements from a list so slow, and is there a faster way?
Each time you remove an element from the list, the elements "shift down" in position. This takes time, as you are essentially recreating (large portions of) the list after each removal. When you create a new list, you build it once. A more Pythonic way to do this is to use a list comprehension. clw = [word for word in words if len(word) == length] More on reddit.com
๐ŸŒ r/learnpython
25
6
April 21, 2024
I was surprised at how slow list.pop() is! And list.remove() is even many times slower
This is simply how lists work, nothing surprising here. Removing the first element requires moving all the elements after it one step to the left to fill that gap, which makes this operation run in linear time. It means that clearing the list this way is O(n2), so it unsurprisingly takes a long time, as bubble sorting the (shuffled) list could even be faster. This is why we think of alternatives when solving problems, such as using collections.deque, reversing the list (O(n) instead of O(n2)) or just using pop() from the end if it works. More on reddit.com
๐ŸŒ r/learnpython
38
57
August 22, 2021
python - Speed of del vs remove on list - Stack Overflow
Assume that I have a list, and I have an element that I want to remove from it. Now suppose I have the index of that element, and I also know exactly what element it is. Would it be faster to do del More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
December 13, 2024 - This cheat sheet is designed to help developers understand the average and worst-case complexities of common operations for these data structures that help them write optimized and efficient code in Python. Python's list is an ordered, mutable sequence, often implemented as a dynamic array. Below are the time complexities for common list operations:
๐ŸŒ
Finxter
blog.finxter.com โ€บ 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
November 1, 2021 - If you specify an element with the wrong index, Python raises an IndexError. li = [3, 5, 7, 2, 6, 4, 8] del li[8] print(li) # IndexError: list assignment index out of range ยท The computational complexity when removing an element in index i from the list of n elements using del is O(n-i). Case ...
๐ŸŒ
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?

๐ŸŒ
UCI
ics.uci.edu โ€บ ~pattis โ€บ ICS-33 โ€บ lectures โ€บ complexitypython.txt
Complexity of Python Operations
Implementation 1: N*O(1) + 10*O(N) = O(N) + O(N) = O(N) Implementation 2: N*O(N) + 10*O(1) = O(N**2) + O(1) = O(N**2) Implementation 3: N*O(Log N) + 10*O(Log N) = O(NLogN) + O(LogN) = O(NLogN) Here, Implementation 1 has the lowest complexity for the combined operations.
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ What-are-the-time-complexity-considerations-of-lists-in-Python
What are the time complexity considerations of lists in Python? - Quora
Answer: In a normal list on average: ... Slice : O(k) * Sort : O(n log n) - n is the length of the list * Len : O(1) * Pop : O(1) - pop from end * Insert : O(n) - n is the length of the list * Del : O(n) - n......
๐ŸŒ
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 is because the list.append() operation simply adds a new element to the end of the list, and the underlying implementation of the Python list data structure is designed to handle this operation efficiently. Here's an example code snippet to demonstrate the constant time complexity of the list.append() operation:
๐ŸŒ
Medium
thinklikeacto.medium.com โ€บ time-complexity-of-popping-elements-from-list-in-python-215ad3d9c048
Time complexity of popping elements from list in Python! | by Naresh Thakur | Medium
January 23, 2020 - 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. Because it just remove the last element and do not need to re-arrange the elements. Python list is implemented as an array of pointers.
๐ŸŒ
Quora
quora.com โ€บ Why-is-the-time-complexity-of-deleting-an-item-from-an-array-linear-O-n-and-not-constant
Why is the time complexity of deleting an item from an array linear - O(n) and not constant? - Quora
This is simply not true: the complexity may be constant depending on your assumptions. What are you planning to accomplish? What is allowed and what is not? What is purposeful and what is accidental? For instance, deleting the last item is most certainly [math]\,O(1)\,[/math] however you choose to do it: maybe you just decrement the length of the array, or you replace the value with a sentinel, etc.
๐ŸŒ
Bradfield CS
bradfieldcs.com โ€บ algos โ€บ analysis โ€บ performance-of-python-types
Performance of Python Types
Now that you have a general understanding of big O notation, weโ€™re going to spend some time discussing the big O performance for the most commonly-used operations supported by Python lists and dictionaries.
๐ŸŒ
GitHub
gist.github.com โ€บ Gr1N โ€บ 60b346b5e91babb5efac
Complexity of Python Operations ยท GitHub
Complexity of Python Operations. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
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 - In this article, we will explore the Big O complexity of common list operations, helping you make informed decisions about algorithm design and performance optimizations. Accessing an element in a Python list by its index is an efficient operation with constant time complexity.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ i was surprised at how slow list.pop() is! and list.remove() is even many times slower
r/learnpython on Reddit: I was surprised at how slow list.pop() is! And list.remove() is even many times slower
August 22, 2021 -

I know there is a list.clear(), I'm just sharing that I didn't expect that using list.pop() and list.remove() specifically could slow down the program that much.

li = list(range(500000))

Creating a list is quick.

So we are going to test out pop/remove specific values. For the purpose of this "benchmark", we are going to remove all elements from the list:

while (li):
    li.pop(0)

It took 74.735 seconds to pop all the elements! It's ridiculously long.
I KNOW it would have been much faster if I even had used li.pop() without the index or maybe used filter function, list comprehension with conditional or whatever
But that's what I'm trying to show, how slow it is to remove certain list items specifically using pop and remove methods.

And li.remove(), which always requires a specified value to remove, is even worse than pop!

 for num in li:
    li.remove(num)

This one took me 303.268 seconds to complete. How crazy it is.

I've been having fun with abstract data structures. Implemented linked lists and a queues running on linked lists.

And for the sake of interest, I decided to compare the performance of the queue based on the linked list and the usual python list. And I was surprised. When my linked list Queue dequeued 500.000 elements in 0.5 seconds, while python list Queue was doing it in 75 seconds.

Top answer
1 of 5
46
This is simply how lists work, nothing surprising here. Removing the first element requires moving all the elements after it one step to the left to fill that gap, which makes this operation run in linear time. It means that clearing the list this way is O(n2), so it unsurprisingly takes a long time, as bubble sorting the (shuffled) list could even be faster. This is why we think of alternatives when solving problems, such as using collections.deque, reversing the list (O(n) instead of O(n2)) or just using pop() from the end if it works.
2 of 5
13
Just thought I'd mention that, on top of being the slowest option presented here, for num in li: li.remove(num) is also broken; it skips every other value in the list and the result is essentially only half of the original list, not an empty one. The reason for this already came up in the other answers, as the values shift in the list when you remove one, but the loop itself doesn't take this into account. You can think of the loop as if it had a hidden index variable it updates on every iteration, and when the values are shifted what was previously going to be the next value after deletion is now where the deleted one was, the loop index goes up by one, and the next index to be removed is the one next to the current one. EDIT: It's easier to understand visually, I guess. idx | 0 | 1 | 2 | 3 | 4 | val | 1 | 2 | 3 | 4 | 5 Loop index: 0 Removing item at index 0 idx | 0 | 1 | 2 | 3 | 4 | val | 2 | 3 | 4 | 5 | ... Loop index: 1 Removing item at index 1 idx | 0 | 1 | 2 | 3 | 4 | val | 2 | 4 | 5 | ... | ... Loop index: 2 Removing item at index 2 Idx | 0 | 1 | 2 | 3 | 4 | val | 2 | 4 | ... | ... | ... EDIT #2: If you needed to empty a list in a real project, the best options would be to either reassign an empty list, or use list.clear which is way faster than using list.pop in a loop.
๐ŸŒ
DEV Community
dev.to โ€บ williams-37 โ€บ understanding-time-complexity-in-python-functions-5ehi
Understanding Time Complexity in Python Functions - DEV Community
October 25, 2024 - Pythonโ€™s built-in sorting algorithm (Timsort) has a time complexity of O(n log n) in the average and worst cases. ... Retrieving a value by key in a dictionary is a constant time operation due to the underlying hash table implementation.
๐ŸŒ
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 ... is : [1, 4, 3, 6] Time complexity: O(1) Auxiliary space: O(1) Method #3 : Using slicing + len() method ยท...