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 ?

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

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]:

Thanks,that helped

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.