If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?
Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.
If a two-dimensional list (a list of lists) is passed directly to len() , the number of lists stored as elements is returned. The number of items in each list (the number of items in each row) can be obtained using the list comprehensions. The total number of items can be calculated with sum() .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With