Python - Count elements in list

PythonList

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

http://docs.python.org/library/functions.html#len">`len()`</a>

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

Solution 2 - Python

just do len(MyList)

This also works for strings, tuples, dict objects.

Solution 3 - Python

len(myList) should do it.

len works with all the collections, and strings too.

Solution 4 - Python

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.

Solution 5 - Python

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

Solution 6 - Python

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

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

>>> l.__len__() 
3

Solution 7 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBruceView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonSrikar AppalarajuView Answer on Stackoverflow
Solution 3 - PythonwinwaedView Answer on Stackoverflow
Solution 4 - PythonAtul ArvindView Answer on Stackoverflow
Solution 5 - PythonJoyfulgrindView Answer on Stackoverflow
Solution 6 - PythonAbdul MajeedView Answer on Stackoverflow
Solution 7 - Pythonuser2373650View Answer on Stackoverflow