Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, what does len(list) do?

Tags:

python

list

Does len(list) calculate the length of the list every time it is called, or does it return the value of the built-in counter?
I have a context where I need to check the length of a list every time through a loop, like:

listData = []
for value in ioread():
    if len(listData)>=25:
        processlistdata()
        clearlistdata()
    listData.append(value)

Should I check len(listData) on every iteration, or should I have a counter for the length of the list?

like image 430
asdfg Avatar asked Mar 08 '10 07:03

asdfg


2 Answers

Help on built-in function len in module __builtin__:

len(...)
    len(object) -> integer

    Return the number of items of a sequence or mapping.

so yes, len(list) returns how many items in the list. You might want to describe in more details, providing necessary input files/output to help better understand what you want to do.

like image 161
ghostdog74 Avatar answered Sep 22 '22 15:09

ghostdog74


You should probably be aware, if you're worried about this operation's performance, that "lists" in Python are really dynamic arrays. That is, they're not implemented as linked lists, which you generally have to "walk" to compute a length for (unless stored in a header).

Since they already need to store "bookkeeping" information to handle memory allocation, the length is stored too.

like image 29
unwind Avatar answered Sep 21 '22 15:09

unwind