Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the big-o notation for the `len()` function in Python? [duplicate]

Tags:

python

big-o

Possible Duplicate:
Cost of len() function

Does len() iterate over the objects in a list and then return their count? Thus giving it a O(n).

Or....

Does a python list keep a count of any objects that are appended to it and removed from it and then simply return this "count" when len() is called? Thus giving it O(1).

like image 511
mjgpy3 Avatar asked Sep 09 '12 19:09

mjgpy3


2 Answers

A Python list knows its own length; len takes O(1) time. Lists are actually arrays, not linked lists as in Lisp, where length takes linear time.

like image 126
Fred Foo Avatar answered Oct 14 '22 13:10

Fred Foo


For all built-in objects that define __len__(), it will be O(1). If you implement __len__() for your own objects, it might be anything.

like image 41
Sven Marnach Avatar answered Oct 14 '22 14:10

Sven Marnach