Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to say array[i+1] in python using for loop

I wrote this code in JavaScript:

let b = [10, 20, 3, 4, 5, 30, 44, 90, 100];
let pairNum = 0;

for (let i = 0; i < b.length; i++) {
  if (b[i] % 10 == 0) {
    if (b[i + 1] % 10 == 0) {
      pairNum+= 1;
    }
  }
}
console.log(pairNum);

But I can’t write the same code in Python because b[i+1] is not allowed. Does anyone know how to write it similar in Python?

This is my code in Python :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b = [10, 20, 3, 4, 5, 30, 44, 90, 100]
pairNum= 0

for i in range (1, len(b)):
    if(b[i]%10 == 0):
        if(b[i+1]%10 == 0):
            pairNum+= 1
        
            
print(pairNum)

>Solution :

Change range(1, len(b)) to range(len(b)-1).

Your code is ignoring the first element because it starts the iteration at i = 1, and trying to access the element after the last element.

Or you could keep your existing range, and use b[i-1] and b[i] instead of b[i] and b[i+1].

You can also use zip() to pair each element with the following element. Since zip() stops when it gets to the end of the shortest input, you won’t go outside the list.

for curnum, nextnum in zip(b, b[1:]):
    if curnum % 10 == 0 and nextnum % 10 == 0:
        pairNum += 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading