Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the runtime complexity of python list functions?

I was writing a python function that looked something like this

def foo(some_list):    for i in range(0, len(some_list)):        bar(some_list[i], i) 

so that it was called with

x = [0, 1, 2, 3, ... ] foo(x) 

I had assumed that index access of lists was O(1), but was surprised to find that for large lists this was significantly slower than I expected.

My question, then, is how are python lists are implemented, and what is the runtime complexity of the following

  • Indexing: list[x]
  • Popping from the end: list.pop()
  • Popping from the beginning: list.pop(0)
  • Extending the list: list.append(x)

For extra credit, splicing or arbitrary pops.

like image 773
Marquis Wang Avatar asked Jun 17 '09 07:06

Marquis Wang


People also ask

What is the time complexity of list in Python?

Here is the summary for in : list - Average: O(n) set/dict - Average: O(1), Worst: O(n)

What is the runtime of the in function in Python?

The average time complexity of the in operator for sets is O(1) . It does not depend on the number of elements. The execution time does not change depending on the value to look for. If you want to repeat in operation for a list with many elements, it is faster to convert it to a set in advance.

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.

Is Len in Python O 1?

Hence, len() function in Python runs in O(1) complexity.


2 Answers

there is a very detailed table on python wiki which answers your question.

However, in your particular example you should use enumerate to get an index of an iterable within a loop. like so:

for i, item in enumerate(some_seq):     bar(item, i) 
like image 183
SilentGhost Avatar answered Sep 21 '22 00:09

SilentGhost


The answer is "undefined". The Python language doesn't define the underlying implementation. Here are some links to a mailing list thread you might be interested in.

Also, the more Pythonic way of writing your loop would be this:

def foo(some_list):    for item in some_list:        bar(item) 
like image 40
anthony Avatar answered Sep 22 '22 00:09

anthony