Hello ,I want to find between what numbers of a list exist a specific number:
For example if i enter 15,i should be between 13 and 21.

list = [1,5,9,11,13,21,27,29,32]

for index in range(len(list)):
  if num > list[index] and num < list[index + 1]:

But with this code when i get to the last element of the list you get the error: list index out of range,because of the list[index + 1]
Any other way to do this ?

6 Years
Discussion Span
Last Post by -ordi-

Use index = bisect.bisect(list, num) . The list must be sorted. Also, don't use 'list' as a variable name.

Edited by Gribouillis: n/a


Start with the second element and use index-1. Also, you should check for less than the first element as well as greater than the last element.

nums_list = [1,5,9,11,13,21,27,29,32]
for index in range(1, len(nums_list)):
    if num > nums_list[index-1] and num < nums_list[index]:
    ## or
    if nums_list[index-1] < num < nums_list[index]:
l = [1,5,9,11,13,21,27,29,32]

num = 15

for index in range(len(l) - 1):
  if (num > l[index]) and (num < l[index + 1]):
    print index, l[index], l[index + 1]

or use (len(l) - 1)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.