-2

I have a list say x = ['abc','cde','tar','har','yyu'] I want to count the number of times 'abc' or 'tar' came, what I am trying to find is something like

count1 = x.count('abc'or'tar')
print(count1)

I want the answer to be 2 but the answer is coming 1. I have searched other codes in Stack Overflow. is there another way of doing it?

4 Answers 4

2

How about this?

count1 = x.count('abc') + x.count('tar')
print(count1)
1

x.count('abc' or 'tar') gives you 1 because 'abc' or 'tar' = 'abc' and your search is equal to x.count('abc')
The simplest way is x.count('abc')+x.count('tar')

1

The use of or is not what you think... The Pythonic evaluation of 'abc' or 'tar' is 'abc', so your code is effectively the same as:

count1 = x.count('abc')
print(count1)

To get the sum of both, you have to call the count() routine for each string searched for. So you could use:

count1 = x.count('abc') + x.count('tar')
print(count1)

If you wanted to check for multiple strings, you could do a simple loop like:

count = 0
for stringy in ('abc', 'tar',): # and others
    count += x.count(stringy)
print(count)
2
  • thank you. but this was an example. what I am trying to do is read from a text file. say (1) 'abc','edf' (2) 'abc','tar'. now 'abc' came 2 times and 'tar' came 1 time. for (2) 'abc' and 'tar' both came so I dont want to double count them. I want to count them once if they both came. so I want my answer here to be 2 but using + operator gives me 3. Jan 14, 2021 at 16:44
  • @SataMukherjee - What you're talking about now is logic different than what you posted in your question. I think I have answered your original Q. If you need further assistance, please post a new Q.
    – GaryMBloom
    Jan 15, 2021 at 3:23
0

list.count only accept single value as argument.

count(value, /) method of builtins.list instance
    Return number of occurrences of value.

You could use the solution provided by @adrtam or you could use sum function with generator expression.

>>> x = ['abc','cde','tar','har','yyu']
>>> sum(1 for i in x if i in ('abc', 'tar'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.