Finding different previous value in a list in python?

Question:

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.

Asked By: yktrcn

||

Answers:

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)
Answered By: Dani Mesejo

Another solution would be to transfer the list into a dict (dicts are guaranteed to be ordered since Python 3.7), reconvert the resulting keys into a list and take the second last item:

>>> l = [1,7,9,8,5,5,5,5,5,5,5,5,5]
>>> list(dict.fromkeys(l))[-2]
8

Note: this is probably quite slow for larger lists and not that readable, but I thought it would be fun

Answered By: user8408080
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.