Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

methods

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?

like image 486
Nasrin Avatar asked Oct 25 '14 13:10

Nasrin


1 Answers

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.

like image 114
Martijn Pieters Avatar answered Oct 29 '22 19:10

Martijn Pieters