tags:

views:

179

answers:

4

My doubt is that if the len(list) calculates the length of the list everytime it is called or it returns the value of the builtin counter.
I have a context where i need to check the length of list everytime in a loop, like

listData = []
for value in ioread():
    if len(listData)>=25:
        processlistdata()
        clearlistdata()
    listData.append(value)
Should I check len(listData) every iteration, or can I have a counter for the length of the list.

+2  A: 
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.

ghostdog74
The OP is worried about whether this length will be recalculated every time it's asked for.
Chris Lutz
i think it also depends on what ioread() does.
ghostdog74
A: 

len(list) returns the length of a list. If you change it, you'll have to check it's length every iteration. Or use a counter.

iTayb
A: 

len(list) returns the length of the list. Everytime you call it, it will return the length of the list as it currently is. You could set up a counter by taking the len of list initially and then adding 1 to the variable each time something is appended to the list.

Protean
+5  A: 

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.

unwind