dunstorm
dunstorm

Reputation: 392

Get the number of same string in a list

I want to get the no. of same string in a list

Example

list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)

Output

2

I have tried this so far

def getnumber(string_var,list):
      if any(string_var in s for s in list):
            print("This user exits !")

Upvotes: 0

Views: 96

Answers (3)

Mestica
Mestica

Reputation: 1529

Use Counter from collections:

list = ['jack','jeen','jeen']
count = Counter(list)
print(count['jeen'])

Upvotes: 3

Eric S
Eric S

Reputation: 1031

Try just using a simple counter function. The idea is to loop through the list you have. In each iteration you are checking whether or not the name you are looking at is equal to 'jeen' in this case. If it is increment your counter, otherwise just move onto the next name. Below is an example:

listNames = ['jack','jeen','jeen']
    occurrences = 0
    for i in listNames:
        if(i == 'jeen'):
            occurrences += 1
    print(occurrences)

Upvotes: -2

Barmar
Barmar

Reputation: 781058

There's a built-in method count that does this.

number_of_jeen = list.count('jeen')

Upvotes: 6

Related Questions