In python, what does len(list) do?

后端 未结 4 1207
耶瑟儿~
耶瑟儿~ 2021-02-19 23:51

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 c

相关标签:
4条回答
  • 2021-02-20 00:43

    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.

    0 讨论(0)
  • 2021-02-20 00:49

    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.

    0 讨论(0)
  • 2021-02-20 00:51
    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.

    0 讨论(0)
  • 2021-02-20 00:51

    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.

    0 讨论(0)
提交回复
热议问题