Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: determine if all items of a list are the same item [duplicate]

Tags:

python

list

In some of my code I put a series of objects in a list and I build an additional list out of their attributes, which is a string. I need to determine if all the items in this second list have the exact same value, without knowing beforehand which value it is, and return a bool so that I can do different things in my code depending on the result.

I can't know the names of the properties beforehand, that is why I'm trying to make something as generic as possible.

To make the example clear, an ideal function, called "all_same" would work like this:

>>> property_list = ["one", "one", "one"] >>> all_same(property_list) True >>> property_list = ["one", "one", "two"] >>> all_same(property_list) False 

I was thinking of making a list of unique elements and then check if its length is 1, but I'm not sure if it's the most elegant solution out there.

like image 681
Einar Avatar asked Sep 24 '10 14:09

Einar


People also ask

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

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

How do you find the number of repeated values in a list in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.

Can a list have duplicate values in Python?

Python list can contain duplicate elements.


2 Answers

def all_same(items):     return all(x == items[0] for x in items) 

Example:

>>> def all_same(items): ...     return all(x == items[0] for x in items) ... >>> property_list = ["one", "one", "one"] >>> all_same(property_list) True >>> property_list = ["one", "one", "two"] >>> all_same(property_list) False >>> all_same([]) True 
like image 57
FogleBird Avatar answered Oct 13 '22 06:10

FogleBird


You could cheat and use set:

def all_same( items ):     return len( set( items ) ) == 1 #== len( items ) 

or you could use:

def all_same( items ):     return all( map(lambda x: x == items[0], items ) ) 

or if you're dealing with an iterable instead of a list:

def all_same( iterable ):     it_copy = tee( iterable, 1 )     return len( set( it_copy) ) == 1 
like image 37
wheaties Avatar answered Oct 13 '22 05:10

wheaties