Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python use linked lists for lists? Why is inserting slow?

Tags:

python

Just learning Python. Reading through the official tutorials. I ran across this:

While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

I would have guessed that a mature language like Python would have all sorts of optimizations, so why doesn't Python [seem to] use linked lists so that inserts can be fast?

like image 388
loneboat Avatar asked Sep 05 '12 03:09

loneboat


People also ask

Is linked list faster than list Python?

Array list is faster (Python list) most of the time, while linked list gets closer (and faster further) only within 1% length to the list start ( a = round(i / 99) ). So even though Python list needs to shift all the items following the deleted item, it's still faster.

Does Python use linked list for list?

To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn't be confused with a typical function of a linked list.

Why insertion is faster in linked list than array?

Arrays allow random access and require less memory per element (do not need space for pointers) while lacking efficiency for insertion/deletion operations and memory allocation. On the contrary, linked lists are dynamic and have faster insertion/deletion time complexities.

Is a linked list better than list Python?

Linked lists differ from lists in the way that they store elements in memory. While lists use a contiguous memory block to store references to their data, linked lists store references as part of their own elements.


2 Answers

Python uses a linear list layout in memory so that indexing is fast (O(1)).

like image 122
Greg Hewgill Avatar answered Sep 21 '22 00:09

Greg Hewgill


list is implemented as an arraylist. If you want to insert frequently, you can use a deque (but note that traversal to the middle is expensive).

Alternatively, you can use a heap. It's all there if you take the time to look at the docs.

like image 38
Marcin Avatar answered Sep 19 '22 00:09

Marcin