0

In a given list

example = ["james:6823", "barry:8263", "henry:2344", "james2342"]

How would I check how many times the name "james" has occurred on the above list?

Shawn Hemelstrand
  • 2,676
  • 4
  • 17
  • 30
  • 1
    Does this answer your question? [Most pythonic way of counting matching elements in something iterable](https://stackoverflow.com/questions/157039/most-pythonic-way-of-counting-matching-elements-in-something-iterable) – Ture Pålsson Feb 25 '23 at 13:16

3 Answers3

3

We could use a list comprehension approach:

example = ["james:6823", "barry:8263", "henry:2344", "james2342"]
count = len([x for x in example if "james" in x])
print(count)  # 2
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 3
    Or `sum("james" in x for x in example)` This does not require to materialize the list of matching items. – Bakuriu Feb 25 '23 at 13:27
  • This would include all names containing "james", not only equal to "james". It would probably be better to split each string. – Thierry Lathuille Feb 25 '23 at 16:08
2

If for some reason you don't want to use list comprehension, you can use:

example = ["james:6823", "barry:8263", "henry:2344", "james2342"]

count = 0
for entry in example:
    if "james" in entry:
        count += 1
print(count)
decuclasho
  • 21
  • 3
1
"""
To check how many times the name "james" occurs on the above list.  
For eg : Here, james:6823 will be considered as 1 item. Again, james2342 will also be considered
as an item. Hence, total 2 items.
"""

aa = ["james:6823", "barry:8263", "henry:2344", "james2342"]

res = sum(1 for x in aa if x.startswith("james"))

print(res) #2

"""
To check how many strings are equal to the name "james" occurs on the above list using split.
For eg : Here, james:6823 will be considered as 1 item. But, james2342 will not be considered.

"""
res1= sum(1 for x in aa if x.split(':')[0] == 'james')
print(res1) # 1
Soudipta Dutta
  • 1,353
  • 1
  • 12
  • 7