6

Possible Duplicate:
Cost of len() function

How Python calculates length of a list(using len() function )?Does it go through a for or while loop to do the same or it has some internal variable that stores the length of the list ?

Community
  • 1
  • 1
  • http://stackoverflow.com/questions/1115313/cost-of-len-function – eugene_che Nov 11 '11 at 09:02
  • “How is `x` implemented” and “What's the cost of `x`” are two different questions with different answers. – Petr Viktorin Nov 11 '11 at 09:55
  • 1
    @Petr: Except that the cost of `x` offers a pretty big clue as to how `x` is implemented. If `len` runs in O(1), for example, you can be pretty sure that there's an internal variable; O(N) probably means it counts them individually; and higher means the Python devs were idiots. :) – cHao Nov 11 '11 at 18:02

4 Answers4

5

Yes, CPython lists have an internal variable for the length.

It's called ob_size; all variable-sized objects have it.

Petr Viktorin
  • 65,510
  • 9
  • 81
  • 81
5

It uses an internal variable that stores the length of the list (as do all other variable-length object types in Python). So len() is an O(1) operation regardless of the size of the list (i.e. it runs in constant time).

Here's the implementation of len() for lists, here's the Py_SIZE macro it calls, and here's the declaration of ob_size that Py_SIZE uses.

Simon Whitaker
  • 20,506
  • 4
  • 62
  • 79
4
a = range(10)
b = range(1000000)

timeit len(a) # 85.4 ns
timeit len(b) # 94.4 ns

It doesn't look like a loop.

eumiro
  • 207,213
  • 34
  • 299
  • 261
3

From python's view, the len() function calls the class's __len__() method, which returns the internally known length.

glglgl
  • 89,107
  • 13
  • 149
  • 217