[Tutor] all elements equal in tuple or list
Kent Johnson
kent37 at tds.net
Thu Nov 18 18:15:43 CET 2004
Bob Gailer wrote:
> At 08:06 AM 11/18/2004, Kent Johnson wrote:
>> 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
A little shorter, but it has to copy vals[1:] and it deferences vals[0]
each time through the loop.
You could write mine as
def test(vals):
if vals:
i = iter(vals)
first = i.next()
for item in i:
if first != item:
return False
return True
and yours as
def test(vals):
if vals:
first = vals[0]
for item in vals[1:]:
if first != item:
return False
return True
which shows that they are very similar.
For short lists, I doubt it makes much difference which one you use. For
longer lists, I expect mine would have an edge but I haven't tested that
assumption!
Kent
>
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625 home
> 720 938 2625 cell
>
More information about the Tutor
mailing list