David Greydanus
David Greydanus

Reputation: 2567

How to find number of instances of an item in a python list

I want to part of a script to be something like this.

if list[1] is in list.pop n times:
      return True

Upvotes: 0

Views: 467

Answers (3)

zhangyangyu
zhangyangyu

Reputation: 8610

Or you can use Counter:

>>> from collections import Counter
>>> Counter([1, 2, 3, 1, 1])
Counter({1: 3, 2: 1, 3: 1})
>>> 

This is good if you want to get all the counts of the distinct elements in the list one time.

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113905

Number of items in a list:

len(myList)

Number of times the ith element occurs in a list:

myList.count(mylist[i])

Upvotes: 2

mishik
mishik

Reputation: 10003

Simply use:

list.count(element)

Example:

>>> [1,2,3,4,2,1].count(1)
2

Upvotes: 7

Related Questions