# [Tutor] how to identify a list element is in the range of a tuple element or a list element

Kent Johnson kent37 at tds.net
Thu Nov 17 15:53:10 CET 2005

```Srinivas Iyyer wrote:
> Dear group,
>
> I have a list of numbers:
>
> a = [10,3,4.6,2.3,4.8,10.8,4.1]
> b = ['1-4','4.1-8','8.1-12','12.1-16']
> c = ((1,4),(4.1,8),(8.1-12),(12.1,16))
>
> Now I want to find if elements of list a are in the
> range of list b and in the range of tuple b.
>
> I know (and my limited knowledge on range function) is
> not allowing me to think of a new way.
>
>
> I wish to have the answer as:
>
> 10   8.1-12
> 3    1-4
> etc.
>

A brute-force approach is straighforward. I ignore b since it has the same values as c, and I corrected the third entry in c to be a tuple.

>>> a = [10,3,4.6,2.3,4.8,10.8,4.1]
>>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16))
>>> for x in a:
...   for lower, upper in c:
...     if lower <= x <= upper:
...       print '%-5s%s-%s' % (x, lower, upper)
...
10   8.1-12
3    1-4
4.6  4.1-8
2.3  1-4
4.8  4.1-8
10.8 8.1-12
4.1  4.1-8

If a and c are large this could be slow, it could be optimized by searching in c instead of exhaustive search, or by terminating the inner loop when a match is found or when lower > x.

Kent

--
http://www.kentsjohnson.com

```