David542 David542 - 6 months ago 25
Python Question

See if all items in a list = certain string

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

x = ['hello', 'hello', 'hello']
# evaluates to True

x = ['hello', '1']
# evaluates to False


This ought to 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):

Nice thing about the all built-in is that it stops on the first item it finds that doesn't meet the condition. This means it is quite efficient with large lists.

Also, if all of the items in the list are strings, then you can use the lower method of a string to match things like `'HellO', 'hELLO', etc.

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