Python - Count elements in list
Advertisement
Python - Count elements in list
Question
I am trying to find a simple way of getting a count of the number of elements in a list:
MyList = ["a", "b", "c"]
I want to know there are 3 elements in this list.
2020/05/04
Read more… Read less…
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.
2013/09/09
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
2013/09/09
You can get element count of list by following two ways:
>>> l = ['a','b','c']
>>> len(l)
3
>>> l.__len__()
3
2020/01/18
Licensed under CC-BY-SA with attribution
Not affiliated with Stack Overflow
Email: [email protected]