I have two lists both containing numbers, and I want to check if the numbers from one list are numbers between every two numbers from the other list? The “other” list has ordered numbers so that every two numbers is an interval like 234, 238, 567, 569, 2134, 2156.
ListA = [200, 765, 924, 456, 231]
ListB = [213, 220, 345, 789, 12, 45]
I want to check if ListA[0:] is a number between either ListB[0:1] or [2:3] etc.
I have tried this:
for i in range(0,len(ListB), 2):
for x in ListA:
if i < x < (i:i+2):
print 'within range'
But I get a syntax error for the “i:i+2” 🙁
I think this is what you want, although it’s not that clear:
You’re right in your intuition that you can
i:i+2sort of represents a “range”, but not quite like that. That syntax can only be used when slicing alist:ListB[i:i+2]returns a smaller list with just 2 elements,[ListB[i], ListB[i+1]], just as you expect, buti:i+2on its own is illegal. (If you really want to, you can writeslice(i, i+2)to mean what you’re aiming at, but it’s not all that useful here.)Also, from your description, you want to compare
xto the valuesListB[i]andListB[i+1], not justiandi+1as in your code.If you wanted to use the slice to generate a range, you could do so, but only indirectly, and it would actually be clumsier and worse in most ways:
But this is checking for a half-open range rather than an open range, and it requires creating the list representing the range, and walking over the whole thing, and it will only work for integers. So, it’s probably not what you want. Better to just explicitly use
ListB[i] < x < ListB[i+1].You might want to consider whether there’s a more readable way to build a list of pairs of elements from
ListB. Without yet knowing aboutitertoolsand list comprehensions or generator expressions (I assume), you’d probably have to write something pretty verbose and explicit, but it might be useful practice anyway.