algorithm - Why does Python take O(n) time to remove the first element from a list? -


the python wiki page on time complexity says deleting item takes o(n) time. description of deque class in documentation of collections module says "list objects [...] incur o(n) memory movement costs pop(0) , insert(0, v) operations change both size , position of underlying data representation".

why lists need o(n) time? isn't list bunch of elements, or pointers elements, physically next each other in memory, along pointer list starts? if so, why can't list type have popleft method, similar 1 in collections.deque, removes first element in o(1) time appropriately incrementing start pointer of list?

i not trying solve specific problem. want satisfy curiosity why designed way.

edit: here diagram of how popleft method work:

before calling popleft:

------------------------------------------------------------------- |      |  quick   |  brown   |   fox    |  jumps   |   on   | -------------------------------------------------------------------       ^       pointer list 

after calling popleft:

------------------------------------------------------------------- |      |  quick   |  brown   |   fox    |  jumps   |   on   | -------------------------------------------------------------------                  ^                  pointer list 

before call popleft, first element of list the, 2nd quick, etc. after call, place first element unused memory (which may left empty or claimed garbage collector), new first element quick, new 2nd element brown, etc. no large amount of data needs moved, , nothing needs happen takes o(n) time.

the pointer list really starts must retained purpose of freeing memory appropriately.

indeed, remove(0) made faster having second pointer increased in case. , if .add(0, x) happens afterwards, made faster decrementing "data start timer" long bigger "memory start timer".

but other operations, i. e. insertions , deletions other indexes, still o(n), wouldn't change much.

just know operations , data structure pick.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo