0

Hope this isn't a stupid question.
Im trying to avoid typing out a long statement many times. As the title says, can I check a range of array elements against a criteria in one small statement?

I'm trying to get something like this: if array[1]...array[4] == 0: Something here...

I am aware I can type out 'array[1] =0 and array[2] = 0' etc, but it seems very tedious.

Many thanks!

(I apogize if this post is badly formatted, the mobile interface isn't that great)

Aaron165
  • 59
  • 10

3 Answers3

3

You may use all() and any() built-in functions with slice syntax.

if all(i == 0 for i in seq[1:4]):  # for elements with indices between 1 and 4
    pass  # do something

if any(s.startswith('a') for a in str_list[1:2:35]):  # for elements with indices 1, 3, 5 etc. up to 35
    pass  # do something
# etc...
Community
  • 1
  • 1
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0

Sure you can!

This is the power of loops :

for x in range(0, len(array)) :     #loops for each array element
    if array[x] == 0 :              #if any element is == 0 then
        print "hooray!"

Don't forget that arrays (or 'lists' in python) are indexed beginning at [0]. The range can also be changed easily if you want to avoid certain sections of the list.

tombam95
  • 343
  • 2
  • 14
0

To check if 0:4 elements of array contains zeros, try condition like below:

if array[0:4] == [0]*4:
ziollek
  • 1,973
  • 1
  • 12
  • 10