Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding different previous value in a list in python?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading