298

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.

iliketocode
  • 6,978
  • 5
  • 46
  • 60
Bruce
  • 3,069
  • 2
  • 14
  • 3
  • 4
    Unfortunately, it seems this is the first google result for `python list check number of elements`, instead of the linked question that this duplicates. – Drise Dec 14 '17 at 17:03

7 Answers7

430

len()

>>> someList=[]
>>> print len(someList)
0
Charlie
  • 8,084
  • 1
  • 51
  • 52
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
102

just do len(MyList)

This also works for strings, tuples, dict objects.

Srikar Appalaraju
  • 69,116
  • 53
  • 210
  • 260
57

len(myList) should do it.

len works with all the collections, and strings too.

iliketocode
  • 6,978
  • 5
  • 46
  • 60
winwaed
  • 7,515
  • 6
  • 33
  • 78
42
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.

Atul Arvind
  • 14,947
  • 6
  • 47
  • 56
26

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
Joyfulgrind
  • 2,632
  • 7
  • 31
  • 40
12

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

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

>>> l.__len__() 
3
Community
  • 1
  • 1
Abdul Majeed
  • 2,471
  • 21
  • 25
10

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.

Drise
  • 4,164
  • 5
  • 38
  • 64
user2373650
  • 101
  • 1
  • 2