# How to make a comparison of part of an array with one value

## How to make a comparison of part of an array with one value

Contents

Problem Description:

``````if x[3] > y and x[4] > y and x[5] > y and x[6] > y and x[7] > y and x[8] > y:
...
``````

Do U have a more elegant method to compare it? actually, I have to compare one value with 30 values in the array, do U know a better way to write it?

## Solution – 1

You can use the `all` function:

``````if all(val > y for val in x[3:9]):
``````

## Solution – 2

You can use all function like:
if all(val > y for val in x[3:9]):

## Solution – 3

There are several ways of doing this.

Use any with a slice of your list:

`````` if any(ex<=y for ex in x[3:9]):
# There is an item that is less than or equal to y in that slice
``````

Use all

`````` if all(ex>y for ex in x[3:9]):
# all x[3:9] are > y
``````

Those functions will not tell you which item is greater than x[idx] — only that there exists a condition that is true.

Or if you want the know the index of the first offending item, use next with a generator:

``````x_gr_y_idx=next(i for i in range(3,9) if x[i]>y)
``````

And for all the items in a range that are offending:

``````[(i, x[i]) for i in range(3,9) if x[i]>y]
``````

Using a slice will silently fail (in this scenario) for a slice that is out of range of the list:

``````>>> li=[1,2,3]
>>> [x<6 for x in li[10:14]]
[]
``````

Whereas an index will give an IndexError for a bad index:

``````>>> [li[i]<6 for i in range(10,14)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
IndexError: list index out of range
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.