tags:

views:

411

answers:

7

If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?

+1  A: 

It has to store the length somewhere, so you aren't counting the number of items every time.

Georg
+12  A: 

Don't worry: Of course it saves the count and thus len() on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!

Ferdinand Beyer
+5  A: 

Write your program so that it's clear and easily maintainable. Is your program clearer with a call to ‘len(foo)’? Then do that.

Are you worried about the time taken? Use the ‘timeit’ module in the standard library to measure the time taken, and see if it's significant in your code.

bignose
+2  A: 

A Python "list" is really a resizeable array, not a linked list, so it stores the size somewhere.

Ken
+1  A: 

The question has been answered (len is O(1)), but here's how you can check for yourself:

$ python -m timeit -s "l = range(10)" "len(l)"
10000000 loops, best of 3: 0.119 usec per loop
$ python -m timeit -s "l = range(1000000)" "len(l)"
10000000 loops, best of 3: 0.131 usec per loop

Yep, not really slower.

dF
+7  A: 

And one more way to find out how it's done is to look it up on Google Code Search, if you don't want to download the source yourself.

static Py_ssize_t list_length(PyListObject *a)
{
    return a->ob_size;
}
AKX
+4  A: 

len is an O(1) operation.

George V. Reilly