Get the previous value based on a specific element
I am trying to use a script where we use a list item and then get the previous item.
lst = [1, 3, 4, 6, 8, 10]
next_item = next((x for x in lst if x > 6), None)
print next_item #8
This code works correctly for the element after 6. However, I need the element before 6.
I look in the docs for the prev method but I can't find anything related. Any ideas about this?
Assuming "before" you mean "previous in lst
", there is no need to use such a complicated method. it
lst[lst.index(6) - 1]
will give
4
while this
lst[lst.index(6) + 1]
will give
8
Of course, you should check for any index related errors.
You can flip a reversible list with the opposite condition:
>>> next((i for i in lst[::-1] if i<6),None)
4
If you're looking for the first number greater than 6 in lst
, this is one way to do it:
lst = [1, 3, 4, 6, 8, 10]
lst2 =[]
for num in lst:
if num > 6:
lst2.append(num)
lst2.sort()
print lst2[0]
Output signal 8