[Tutor] all elements equal in tuple or list

Kent Johnson kent37 at tds.net
Thu Nov 18 16:06:00 CET 2004


Here is one way to do it. It should work with any iterable (list, 
tuple...) whose elements can be compared with ==. It compares the first 
element of the iterable with each subsequent element. I thought of a 
couple other ways to do it but I like this one because it doesn't create 
any new data and it returns as soon as it finds a mismatch - it doesn't 
need to compare against the whole list.

Kent

def test(vals):
     if not vals: return True

     i = iter(vals)
     first = i.next()
     for item in i:
         if first != item:
             return False
     return True

vals1 = [1, 1, 1, 1]
vals2 = [1, 2, 1, 1]
vals3 = [2, 1, 1, 1]

print test(vals1)
print test(vals2)
print test(vals3)


Dimitri D'Or wrote:
> Hello list,
> 
> I'm quite new in the Python world and I'm coming from Matlab.
> 
> I have a tuple (or a list) made itself of lists and I want to know if all 
> lists in this tuple are equal. Is there a function to do that ?
> 
> Clearly, I have :
> t=(a,b,c) wherein a,b and c are lists of equal size. (Note that the number of 
> lists in the tuple is arbitrary).
> I want to know if all the lists in the tuple are equal.
> 
> In Matlab, I simply use equal(A,B,C) or equal(D{:}) if D is a cell array 
> containing A, B and C as cells.
> 
> A suggestion for me ?
> 
> Thank you,
> 
> Dimitri
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list