See If all items in a list = specific string

How would I find if I have a list of the given string, 'hello':

x = ['hello', 'hello', 'hello'] # evaluates to True x = ['hello', '1'] # evaluates to False 
+4
source share
5 answers

This should work:

 # First check to make sure 'x' isn't empty, then use the 'all' built-in if x and all(y=='hello' for y in x): 

The good thing about the built-in all is that it stops at the first element found that does not meet this condition. This means that it is effective with large lists.

Also, if all the items in the list are strings, then you can use the lower method for a string like "HellO", "hELLO", etc.

 if x and all(y.lower()=='hello' for y in x): 
+5
source

Use the all() function to check if the True condition is True for all elements:

 all(el == 'hello' for el in x) 

The all() function takes an iterable (something that gives results one by one) and will only return True if all of these elements are true. When he finds something false, he will return False and will not look any further.

Here, iterable is a generator expression that performs an equality test for each element in the input sequence. The fact that all() stops repeating early if a false value is encountered makes this test very effective if the test in the expressed expression of the False generator for any element is at an early stage.

Note that if x empty, then all() returns True , and also will not find any elements that are false in the empty sequence. You can verify that the first sequence is nonempty:

 if x and all(el == 'hello' for el in x): 

to get around this.

+14
source

Another way to do what you want ( all is the most idiomatic way to do this, like all the other answers), is useful if you need to check several times:

 s = set(l) cond = (len(s) == 1) and (item in s) 

This helps to avoid O(n) traversal every time you want to check a condition.

+2
source

Using a filter and len is easy.

 x = ['hello', 'hello', 'hello'] s = 'hello' print len(filter(lambda i:i==s, x))==len(x) 
+1
source

Youn can do this with set :

 set(x) == {'hello'} 
+1
source

Source: https://habr.com/ru/post/1498872/


All Articles