In code below, I get the same result whether I use len
or count
:
fn main() { let vector = [0, 1, 2]; assert_eq!(vector.iter().count(), vector.iter().len()); }
len
seems more generic since I can also do this:
assert_eq!(vector.len(), 3);
So, what's the difference between the two... why use one and not the other?
Definition. The len() Python function counts the number of items in an object. The object can be a string, tuple, dictionary, list, sets, array, and many more. The items here are the elements inside these objects, and the count represents the number of occurrences of these items in an object.
Definition and Usage. The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function.
If we're talking about applying len() to a list, then the values don't matter: all elements will be included in the count. This includes None , NaNs etc.
vector.len()
Returns the number of elements in the vector.
iter.len()
Return the exact length of the iterator.
iter.count()
Counts the number of elements in this iterator.
So while they return the same value, count
will actually count the elements. Note that len
is available only for ExactSizeIterator; so if the value is lazy-retrieved the total length may not be available and you need to explicitly count it.
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