0

I'm trying to iterate through a list using a for loop (the index starts at 0) and I want a certain function to execute every 10th index. However, since I'm grouping the numbers in the list by 10 in that function (for example, 0-9,10-19,20-29 and so on), index%10 doesn't work. Is there a more efficient way of doing this? The code I have below works, but I feel like there is a better way to do it?

if(index>1 and index<10):
    if((index)%9 == 0):
         func()
elif(index>10):
    if((index+1)%10 == 0):
         func()
Lehman2020
  • 637
  • 7
  • 22
  • 1
    I don't understand why neither `index%10` nor `(index+1)%10` works. What does "10th index" mean to you? (I.e. what specific int values do you want this condition to trigger on?) – Samwise Jun 24 '20 at 01:35
  • There is a optional `step` variable that can be passed when you are slicing a list: `list1[start:stop:step]`, do refer to https://stackoverflow.com/a/509295/8350440 – Ji Wei Jun 24 '20 at 01:37

3 Answers3

1

You still use modulo 10 because you want every tenth one, but instead of checking for zero check for 9.

if(index % 10 == 9)

Modulo just gets the remainder of a division. You want 9, 19, 29, and 39. If you take each and divide by 10 what is the remainder? It's 9 in every case.

Delta_G
  • 2,927
  • 2
  • 9
  • 15
1

The test that you are using already in the second part of your code is in fact all that you need:

if (index + 1) % 10 == 0:
    func()

There is no need to test whether index > 10. func() will be called when index = 9, 19, 29, ....

If you wanted, you could write this instead as:

if index % 10 == 9:
    func()

But although the second version might be very slightly quicker to calculate, the first version is cleaner because if for example you want to change from printing every 10th index to every 8th index, then you would only need to change one number in the code (i.e. the number 10 where it appears), so it is more maintainable.

alani
  • 12,573
  • 2
  • 13
  • 23
0

Since the tenth index is represented by 9:

if index % 10 == 9:
    func()
Red
  • 26,798
  • 7
  • 36
  • 58