For a boolean predicate on a list like this, you want a solution that returns False
as soon as a conflict is found -- solutions that convert the entire list just to find the first and second item didn't match aren't good algorithms. Here's one approach:
def all_same_first(a):
return not a or all(map(lambda b, c=str(a[0])[0]: str(b)[0] == c, a[1:]))
Although at first glance this might appear to violate what I said above, the map
function is lazy and so only hands the all
function what it needs as it needs it, so as soon as some element doesn't match the first (initial-digit-wise) the boolean result is returned and the rest of the list isn't processed.
Going back to your original code:
this checks for if the number before is equal to the next
number in the list
for i in range(0,len(lst)-1):
if lst[i] == lst[i+1]:
return True
This doesn't work, as you claim. To work properly, it would need to do:
for i in range(0, len(lst) - 1):
if lst[i] != lst[i + 1]:
return False
return True
Do you see the difference?