Skip to content
Advertisement

How do I reverse a list using while loop?

Input list: [1, 2, 3, 4, 5]

Output: [5, 4, 3, 2, 1]

I know how to do it with for loop, but my assignment is to do it with while loop; which I have no idea to do. Here is the code I have so far:

def while_version(items):
   a = 0

 b = len(items)

 r_list = []

  while (a!=b):

        items[a:a] = r_list[(-a)-1]

        a+=1
   return items

Advertisement

Answer

I would say to make the while loop act like a for loop.

firstList = [1,2,3]
secondList=[]

counter = len(firstList)-1

while counter >= 0:
    secondList.append(firstList[counter])
    counter -= 1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement