[Tutor] all elements equal in tuple or list
Bob Gailer
bgailer at alum.rpi.edu
Thu Nov 18 17:45:09 CET 2004
At 08:06 AM 11/18/2004, Kent Johnson wrote:
>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)
Would not the following be a bit simpler?
def test(vals):
if vals:
for item in vals[1:]:
if vals[0] != item:
return False
return True
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell
More information about the Tutor
mailing list