Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If all in list == something

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() 
like image 526
Zoomulator Avatar asked Jan 01 '09 21:01

Zoomulator


People also ask

How do you check if all elements in a list are equal?

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.

How do I check if a list is in if condition?

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.

How do you check if all values in a list are even Python?

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.

How do you check if all elements in a list are different Python?

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. ")


1 Answers

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.

like image 107
Autoplectic Avatar answered Oct 14 '22 05:10

Autoplectic