Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Count elements in list [duplicate]

Tags:

python

list

People also ask

How do you count the number of repeated elements in a list in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.


len()

>>> someList=[]
>>> print len(someList)
0

just do len(MyList)

This also works for strings, tuples, dict objects.


len(myList) should do it.

len works with all the collections, and strings too.


len() 

it will count the element in the list, tuple and string and dictionary, eg.

>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string 
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple 
>>> len(tup)
3

To learn Python you can use byte of python , it is best ebook for python beginners.


To find count of unique elements of list use the combination of len() and set().

>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4