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 can I print the array in reverse order using while loop? (Python)

I need to print out the array in reverse order without using the reverse(). The output of my code just printed 13. Is there something missing in my code? Still new to python so I’m stumbling about just to figure out how things works.

This is my code:

arr = [1, 3, 5, 7, 9, 11, 13]

def oddNumberReverse(arr):
   i = len(arr) - 1
   while i < len(arr):
       if arr[i] % 2 == 1:
           print (arr[i])
       i += 1
       return (arr)

oddNumberReverse(arr)

The output should be the full array in reverse order but my output is 13.

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

>Solution :

There are quite a few problems in your attempt:

1.Keep the return outside the while loop

2.Take an empty list lst to append values

3.while should go greater than 0

4.append values arr([i]) to lst

arr = [1, 3, 5, 7, 9, 11, 13]

def oddNumberReverse(arr):
   i = len(arr) - 1
   lst = []
   while i > 0:
       if arr[i] % 2 == 1:
           lst.append(arr[i])
       i -= 1
   return lst

oddNumberReverse(arr)

#output
[13, 11, 9, 7, 5, 3]
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