Finding index of newly added element that is numerically ordered
Question:
I’m making a program that gets new numerical values to put into a list in numerical order and I need to know what element is before it in the list or the index before it.
How do I find the index of a newly added element in a list that is ordered numerically?
Answers:
If you have a list that is sorted, you can use the list.index
function to find the index of an element in the list. You then just need to get the element at that index minus one. Assuming the index isn’t zero.
>>> lst = [0, 2, 5, 9]
>>> x = 3
>>> lst.append(x)
>>> lst.sort()
>>> n = lst.index(x)
>>> (n-1, lst[n-1])
(1, 2)
I’m making a program that gets new numerical values to put into a list in numerical order and I need to know what element is before it in the list or the index before it.
How do I find the index of a newly added element in a list that is ordered numerically?
If you have a list that is sorted, you can use the list.index
function to find the index of an element in the list. You then just need to get the element at that index minus one. Assuming the index isn’t zero.
>>> lst = [0, 2, 5, 9]
>>> x = 3
>>> lst.append(x)
>>> lst.sort()
>>> n = lst.index(x)
>>> (n-1, lst[n-1])
(1, 2)