Let’s say i have list output of 500 items. What i want is getting the previous value which is not the same of the last item.
For example:
List = [1,7,9,8,5,5,5,5,5,5,5,5,5]
desired output : 8
I need my code the calculate previous different item. In my list, the last item is 5 and according to previous items, i need the first different number than the last one.
I searched google, but all i could find is the previous item compared to last or previous low/high values in the list which are not helping me at the moment.
Thanks a lot.
>Solution :
One approach using extended iterable unpacking and next:
lst = [1, 7, 9, 8, 5, 5, 5, 5, 5, 5, 5, 5, 5]
last, *front = reversed(lst)
res = next((v for v in front if last != v), None)
print(res)
Output
8
The above approach is equivalent to the following for-loop:
last, *front = reversed(lst)
res = None
for v in front:
if last != v:
res = v
break
print(res)