Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement?
[pseudocode] my_sequence = (2,5,7,82,35) if all the values in (type(i) for i in my_sequence) == int: do()
Instead of, say:
my_sequence = (2,5,7,82,35) all_int = True for i in my_sequence: if type(i) is not int: all_int = False break if all_int: do()
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
Checking if the item exists in the list. To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
Example. # Given List Alist = ['Mon','Tue','Wed'] print("The given list : ",Alist) # Compare length for unique elements if(len(set(Alist)) == len(Alist)): print("All elements are unique. ") else: print("All elements are not unique. ")
Use:
all( type(i) is int for i in lst )
Example:
In [1]: lst = range(10) In [2]: all( type(i) is int for i in lst ) Out[2]: True In [3]: lst.append('steve') In [4]: all( type(i) is int for i in lst ) Out[4]: False
[Edit]. Made cleaner as per comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With