look at this code :
x=object()
x_list=[x]*5
print x_list.count(x)
5
print len(x_list)
5
The output of count()
and len()
is same, What is the difference between them?
list.count()
counts how many times the given value appears. You created a list of 5 elements that are all the same, so of course x_list.count()
finds that element 5 times in a list of length 5.
You could have tried the same test with a list with a mix of values:
>>> sample = [2, 10, 1, 1, 5, 2]
>>> len(sample)
6
>>> sample.count(1)
2
The sample
list contains 6 elements, but the value 1
appears only twice.
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