Coder Cody
Coder Cody

Reputation: 120

How to check if a certain string repeats more than once in a list

In my code, I want to check whether I could check if a certain string e.g

a="."

repeats more than once in a list. e.g

b=[".", ".", "Hello world"]

how would I do that?

Upvotes: 0

Views: 1835

Answers (5)

b-fg
b-fg

Reputation: 4137

Using collections.Counter:

from collections import Counter

a = "."
b=[".", ".", "Hello world"]

print(Counter(b)[a]) # 2

Upvotes: 1

Usman
Usman

Reputation: 2029

Use count function.

    a="."
    b=[".", ".", "Hello world"]
    if b.count(a) > 1:
        print("more than 1 time")

Upvotes: 1

enamoria
enamoria

Reputation: 916

Use collections.Counter() or simply list.count()

list.count(x) will return the count of x in list

b=[".", ".", "Hello world"]
# Check for "."
print(b.count(".")

collections.Counter will return a dictionary, which have count information of every item in a list:

from collections import Counter

b=[".", ".", "Hello world"]
# Check for "."
count = b.Counter() 

if count["."] > 1:
   print("More than one occurance")

Upvotes: 1

Sven Harris
Sven Harris

Reputation: 2939

You can use the built in count method

n_occurences = b.count(a)

Upvotes: 2

Sandesh34
Sandesh34

Reputation: 280

b=[".", ".", "Hello world"]
print(b.count(a))
>>> 2

Use count function.

Upvotes: 3

Related Questions