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?
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?
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
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)
"""
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