Determining whether a variable is less/greater than a range.

simonharrison.uk at googlemail.com simonharrison.uk at googlemail.com
Mon Dec 8 06:27:15 EST 2008


On Dec 8, 11:12 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> > a = list(range(10, 21))
>
> > b = 9
>
> > c = 21
>
> > How can I find out if b and c have values less or more than the values
> > in list a?
>
> Sounds like a good use for 2.5's addition of the any() and all()
> functions -- you don't mention whether you want your variable
> compared against *any* of the list items or *all* of the list
> items.  You also don't mention whether you want the comparison
> results, or just a single scalar.  Lastly, you omit the details
> of what happens if your target value ("d" below) falls within the
> range.  One of the following should do it for you:
>
>    >>> a = range(10,21)
>    >>> b = 9
>    >>> c = 21
>    >>> d = 15
>    >>> any(b < x for x in a)
>    True
>    >>> all(b < x for x in a)
>    True
>    >>> any(c < x for x in a)
>    False
>    >>> any(d < x for x in a)
>    True
>    >>> all(d < x for x in a)
>    False
>    >>> any(c > x for x in a)
>    True
>    >>> all(c > x for x in a)
>    True
>    >>> any(d > x for x in a)
>    True
>    >>> all(d > x for x in a)
>    False
>
> If you just want the comparisons:
>
>    y1 = [b<x for x in a]
>    y2 = [c<x for x in a]
>    y3 = [d<x for x in a]
>    z1 = [(b<x, b>x) for x in a]
>    z2 = [(c<x, c>x) for x in a]
>    z3 = [(d<x, d>x) for x in a]
>
> -tkc

Hi Tim. I'm just learning Python at the moment. All I was really
wanting was a True or False value which min and max give.

a = list(range(10, 21))

b = 9

c = 21

if b < min(a)
if c > max(a)

The any() and all() functions look useful so thanks for the tips.



More information about the Python-list mailing list