开发者

Python - Count elements in list [duplicate]

开发者 https://www.devze.com 2023-01-23 22:32 出处:网络
This question already has answers here: How do I get the number of elements in a list (length of a list) in Python?
This question already has answers here: How do I get the number of elements in a list (length of a list) in Python? (11 answers) Closed 6 years ago.

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 ar开发者_StackOverflow中文版e 3 elements in this list.


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


You can get element count of list by following two ways:

>>> l = ['a','b','c']
>>> len(l)
3

>>> l.__len__() 
3


Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

0

精彩评论

暂无评论...
验证码 换一张
取 消