1

If I have a list of strings such as this:

names = ["Alice", "Bob", "Charlie", "Darren"]

How would I find how many of these strings contain the letter 'a'?

I tried using the count function

names.count("a")

But this only output the amount of elements that were 'a' rather than contained 'a'.

3 Answers3

1

A list comprehension can be used to determine the no. of elements with letter 'a' in them.

print(len([x for x in names if 'a' in x]))

O/P: 2

Sam
  • 643
  • 2
  • 13
  • what's "O/P: 2" ? – gog Nov 27 '22 at 11:58
  • O/P is short for Output. – Sam Nov 27 '22 at 11:59
  • 1
    The suggestion in your note will not save any memory, and likely give a `NameError` unless `_` has been defined somewhere. – Jasmijn Nov 27 '22 at 12:05
  • @Jasmijn Thank you for the memory part. As for _, it won't give NameError as in python 3.11, that I am using. – Sam Nov 27 '22 at 12:19
  • 1
    @Sam It depends on if `_` is defined. In the REPL, it's automatically bound to the last evaluated expression. If you start a fresh REPL and only enter the lines `names = ["Alice", "Bob", "Charlie", "Darren"]` and `print(len([_ for x in names if 'a' in x]))`, you'll get the name error. See [What is the purpose of the single underscore "_" variable in Python?](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python/5893946#5893946). – Jasmijn Nov 27 '22 at 12:23
0

We can use a loop:

names = ["Alice", "Bob", "Charlie", "Darren"]

count=0

for i in range(len(names)):
    if 'a' in list(names[i]):
        count+=1
        
print(count)

Output:

>>> 2 
Khaled DELLAL
  • 871
  • 4
  • 16
  • Iterate over items, not with a range, don"t convert each item to a list, that useless – azro Nov 27 '22 at 11:55
0

Generally, if you want to count how many elements in a list satisfy a condition, you have to iterate the list, that is, check the condition for every element and count successful tries:

names = ["Alice", "Bob", "Charlie", "Darren"]
count = 0

for name in names:
    if 'a' in name:
        count += 1

print(count)

On a more advanced note, recall that boolean values (like a in b) are actually integers in Python and that there's a built-in sum function to which you can pass a generator expression. Combining these ideas, the solution is as simple as:

print(sum('a' in name for name in names))
gog
  • 10,367
  • 2
  • 24
  • 38