Tim
Tim

Reputation: 99428

How can I check if all the elements in a list are the same?

There is a list, whose items are either integers or string NULL. How can I check if the list is all NULL, without checking each item in the list using a loop?

Upvotes: 1

Views: 59

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

Convert the list to a set and compare it like this

>>> set(["NULL", "NULL"]) == {"NULL"}
True
>>> set(["NULL", "NULL", 1]) == {"NULL"}
False

When you convert your list to a set, all the duplicates are removed and only the unique values are retained. Now, you can compare it against another set with just NULL. They both are equal, then your actual list has only NULLs.

Note: Converting to set will only work if all the items in your list are hashable. In your case, you have only numbers and strings. So, you are fine here.


Alternate, and the idiomatic, way would be to use all function (or its sister function any)

>>> all(item == "NULL" for item in ["NULL", "NULL", 1])
False
>>> all(item == "NULL" for item in ["NULL", "NULL"])
True

Here, if the non NULL value is somewhere in the middle, then all will immediately return False and you don't have to check the entire list. Similarly, any can be used with not like this

>>> not any(item != "NULL" for item in ["NULL", "NULL", 1])
False
>>> not any(item != "NULL" for item in ["NULL", "NULL"])
True

Upvotes: 4

Related Questions