0

Python newbie here. Let's say we have an array which contains 10 random integers. I want to check if each value of the integers is 0<= x <= 9. So for example somehow like this:

if 0 <= n[:11]  <=9:
    print('correct')

'n[:10]' is treated like a list so I can't compare it with 0 and 9. Is there an elegant way to check the range of items in that array?

I don't want to code something like:

if 0 <= n[0] and n[1] and ... n[9] <=9:

thanks for your help

2
  • all(0 <= i <= 9 for i in n[:11]) Commented Aug 22, 2021 at 13:54
  • Use a List comprehension, you will have to loop through each element anyways Commented Aug 22, 2021 at 13:55

4 Answers 4

4

Check this out: This returns True if and only if ALL of the numbers in the list n are at least 0 and at most 9, (in range(0, 10))

 all(i in range(0, 10) for i in n)
Sign up to request clarification or add additional context in comments.

Comments

2
if 0 <= min(n) <= max(n) <= 9:

Could use and instead of <= in the middle, not sure which I like better.

Comments

0

What you want is the check the equality for every elements:

all(0 <= item <= 9 for item in n)

Comments

0

If you first sort the list you only have to check the first and last value, like this:

sorted_n = sorted(n)

if sorted_n[0] > 0 and sorted_n[-1] < 10:  # returns True or False for whole list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.