Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between len() and count()?

Tags:

rust

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?

like image 837
tshepang Avatar asked Apr 07 '15 20:04

tshepang


People also ask

What is function of Len and count for list?

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.

What is the function of LEN () method?

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.

Can you use LEN () on a list?

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.

Does Len include Nan?

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.


1 Answers

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.

like image 80
Peter Uhnak Avatar answered Oct 24 '22 04:10

Peter Uhnak