473,387 Members | 1,771 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Algorithmic complexity of len (list)?

Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?
Jul 18 '05 #1
8 4521
On Fri, 02 Jul 2004 19:18:20 -0400, Roy Smith <ro*@panix.com> wrote:
Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?


I'd assume O(1), and the following seems to verify it:

import time
lists = []
for len_power in range(1,8):
lists.append(range(1,10**len_power))
for l in lists:
start = time.time()
length = len(l)
end = time.time()
print "%d\t%f" % (length, end-start)

I'm sure there's a python library that does a much better
job of determining average runtimes, but for this case if
it was O(n) is should show up pretty quick in the output
generated.

The existance of negative indexing strongly implies O(1) as
well, as does the existance of bounds checking when
accessing (rather than random core dumps).

--
Sam Holden
Jul 18 '05 #2
[Roy Smith]
Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?


O(1). Ditto len(tuple), len(dict), len(str), len(unicode), and
len(array.array).

Jul 18 '05 #3
On Fri, 02 Jul 2004 19:18:20 -0400
Roy Smith <ro*@panix.com> threw this fish to the penguins:
Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?


[Python 2.3.3]
timeit.py -s 'l=range(5000)' 'len(l)'
1000000 loops, best of 3: 0.975 usec per loop
timeit.py -s 'l=range(10000)' 'len(l)'
1000000 loops, best of 3: 0.975 usec per loop
timeit.py -s 'l=range(50000)' 'len(l)'
1000000 loops, best of 3: 0.975 usec per loop
timeit.py -s 'l=range(100000)' 'len(l)'
1000000 loops, best of 3: 0.975 usec per loop

Sure looks like O(0) to me.

seems to be the same for strings and tuples.

-- George Young

--
"Are the gods not just?" "Oh no, child.
What would become of us if they were?" (CSL)
Jul 18 '05 #4
In article <ro***********************@reader2.panix.com>,
Roy Smith <ro*@panix.com> wrote:

Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?


Consider that if it weren't, operations such as l.pop() and l[-3:] would
also be O(N)...

(I couldn't resist making a comment because I'm currently using your
..sig. ;-)
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py
Jul 18 '05 #5
In article <cc**********@panix3.panix.com>, aa**@pythoncraft.com (Aahz)
wrote:
In article <ro***********************@reader2.panix.com>,
Roy Smith <ro*@panix.com> wrote:

Is the length of a list stored in the object, or does len() have to
count the elements each time you call it? In other words, is len (list)
O(1) or O(n)?


Consider that if it weren't, operations such as l.pop() and l[-3:] would
also be O(N)...

(I couldn't resist making a comment because I'm currently using your
.sig. ;-)


Well, I take that as meaning, "you really should have been able to
figure that out yourself if you just took the time to think about it".
I disagree. I can guess, I can even make intelligent informed guesses,
but it would still just be a guess.

One could think of implementations where l.pop() and l[-3:] are O(1),
but len(l) is O(n). I could, for example, keep a pointer to the tail of
the list, but not keep track of the number of elements.

Why would somebody want to implement it that way? I don't know, but
it's possible. Maybe they felt that accessing the ends of lists was
something that needed to be done fast, but computing their length
wasn't, and saving the extra bit of memory for each list was important.

Iterators sort of look like lists, but I can't get their length quickly
(or even idempotently, it would appear). If they didn't think getting
the length of an iterator was important, then maybe they didn't think
getting the length of a list was important either.

I can make measurements, or download the source and look at it, but I
shouldn't have to. Likewise, I shouldn't have to engage in a deep
analytic guessing game of what the designer had in mind when designing
the container. I want a tool, not a hobby. One of the (few) things I
like about the C++ STL is that it documents these types of things. Is
there any reason Python couldn't?
Jul 18 '05 #6
Roy Smith <ro*@panix.com> wrote in message news:<ro***********************@reader2.panix.com> ...
analytic guessing game of what the designer had in mind when designing
the container. I want a tool, not a hobby. One of the (few) things I
like about the C++ STL is that it documents these types of things. Is
there any reason Python couldn't?


I believe this has been mentioned before, and the main reason it
hasn't been done may be that no one has done it (yet). As a first
step, somebody should summarize this discussion and add it to the
language reference.
Jul 18 '05 #7
Roy Smith wrote:
(or even idempotently, it would appear). If they didn't think getting
the length of an iterator was important, then maybe they didn't think
getting the length of a list was important either.


They might think *not* getting the length of an iterator is important.

Peter

Jul 18 '05 #8
Roy Smith wrote:
Iterators sort of look like lists, but I can't get their length quickly
(or even idempotently, it would appear).


You can if that particular iterator happens to have an __len__ method. I
would assume that the iterator protocol doesn't require one because that
would make infinite iterators impossible.
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Roy Smith | last post by:
I want to build up a long string piece by piece without the quadratic behavior of string concatenation. I'm looking at the {c,}StringIO modules as a way around this, but I don't see anything in...
12
by: Brett L. Moore | last post by:
Hi, I have had trouble determining whether the STL list.size() operation is O(1) or O(n). I know the list is a doubly-linked list, so if the size() operation begins at the head, then counts to...
4
by: Generic Usenet Account | last post by:
Consider two entities A and B such that there is a 1:n association between them. I mean that associated with each instance of A there are up to n instances of B. Currently in our software we are...
44
by: Josh Mcfarlane | last post by:
Just out of curiosity: When would using std::list be more efficient / effective than using other containers such as vector, deque, etc? As far as I'm aware, list doesn't appear to be...
4
by: Xah Lee | last post by:
i've long time been interested in algorithmic mathematical art. That is, mathematical or algorithmic visual art works that are generated by computer such that the program's source code reflects the...
25
by: Markus Svilans | last post by:
Hi, There seems to be some functionality missing from the STL. I am iterating through a linked list (std::list) using a reverse iterator and attempting to erase certain items from the list. It...
10
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a...
26
by: Lionel B | last post by:
Hi, Anyone know if the Standard has anything to say about the time complexity of size() for std::set? I need to access a set's size (/not/ to know if it is empty!) heavily during an algorithm...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.