I think this is what you want, although it's not that clear:
for i in range(0, len(ListB), 2):
for x in ListA:
if ListB[i] < x < ListB[i+1]:
print 'within range'
You're right in your intuition that you can i:i+2
sort of represents a "range", but not quite like that. That syntax can only be used when slicing a list
: ListB[i:i+2]
returns a smaller list with just 2 elements, [ListB[i], ListB[i+1]]
, just as you expect, but i:i+2
on its own is illegal. (If you really want to, you can write slice(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 x
to the values ListB[i]
and ListB[i+1]
, not just i
and i+1
as 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:
for i in range(0, len(ListB), 2):
brange = range(*ListB[i:i+2])
for x in ListA:
if x in brange:
print 'within range'
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 about itertools
and 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.