Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of list functions in Python

Based on this older thread, it looks like the cost of list functions in Python is:

  • Random access: O(1)
  • Insertion/deletion to front: O(n)
  • Insertion/deletion to back: O(1)

Can anyone confirm whether this is still true in Python 2.6/3.x?

like image 414
Dan Avatar asked Oct 05 '09 18:10

Dan


People also ask

What is the time complexity of list insert Python?

According to Python's official Time Complexity page1, using list. insert always has O(n) (linear) complexity.

What is the time complexity of list insert?

Python List insert() Time Complexity. The time complexity to insert an element at a given index is O(n). This means that the complexity increases linearly with the number of elements in the list.


2 Answers

Take a look here. It's a PEP for a different kind of list. The version specified is 2.6/3.0.

Append (insertion to back) is O(1), while insertion (everywhere else) is O(n). So yes, it looks like this is still true.

Operation...Complexity
Copy........O(n) 
Append......O(1)
Insert......O(n) 
Get Item....O(1)
Set Item....O(1)
Del Item....O(n) 
Iteration...O(n)
Get Slice...O(k)
Del Slice...O(n)
Set Slice...O(n+k)
Extend......O(k) 
Sort........O(n log n)
Multiply....O(nk)
like image 161
ryeguy Avatar answered Oct 03 '22 05:10

ryeguy


Python 3 is mostly an evolutionary change, no big changes in the datastructures and their complexities.

The canonical source for Python collections is TimeComplexity on the Wiki.

like image 22
u0b34a0f6ae Avatar answered Oct 03 '22 04:10

u0b34a0f6ae