# Range checking a list

Can anyone help me with an elegant way to range check a list?

I tried this:

``````>>> chk_range = [range(0,30), range(0, 50), range(0, 100)]
>>> [20, 30, 40] in chk_range
False``````

But as you can see it returns False. I guess this is because I’m checking if a specific list exists rather than whether each element of the list exists within the corresponding element of chk_range, but I don’t know an elegant way to do this.

Just to add a bit more clarity, what I’m try to do is check whether each element of my list is within the corresponding range specified in chk_range[…], so something more elegant than this?

``````valid = True
mylist = [35, 30, 40]
chk_range = [range(0, 30), range(0, 50), range(0, 100)]

for index in range(len(mylist)):
if mylist[index] not in chk_range[index]:
valid = False
break

print(valid)``````

Try a simpler testing and learn from the result. For example:

This does not gives the result you expect:

``````chk_range = [1,2,3]
if [1, 2, 3] in chk_range:
print('hello')    print('hello')
``````

This gives something similar to what you expect:

``````chk_range = [1,2,3]
if 3 in chk_range:
print('hello')``````

Thanks for the sound advice Ricardo, it always makes sense to break things down and test small bits to see if they behave as expected, which they didn’t!

I have updated my question with a piece of code that does what I expect it to do and so I’m wondering if there is a more compact way of achieving the same result.

what are you talking about? what code?

This code which I added to my original post above.

``````valid = True
mylist = [35, 30, 40]
chk_range = [range(0, 30), range(0, 50), range(0, 100)]

for index in range(len(mylist)):
if mylist[index] not in chk_range[index]:
valid = False
break

print(valid)``````

Can not think of any way to compact it more

You will want to check out https://docs.python.org/2/library/sets.html and https://docs.python.org/3/library/functional.html for ways to do this better. Basically you make a set of all the numbers in the ranges then you do set operations or checks if they are in.

1 Like