Home > Blockchain >  Finding different previous value in a list in python?
Finding different previous value in a list in python?

Time:07-30

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.

CodePudding user response:

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)

CodePudding user response:

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

  • Related