BongWater
BongWater

Reputation: 5

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

Upvotes: 0

Views: 15113

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122024

The simplest way would be:

def while_version(items):
    new_list = []
    while items:  # i.e. until it's an empty list
        new_list.append(items.pop(-1))
    return new_list

This will reverse the list:

>>> l1 = [1, 2, 3]
>>> l2 = while_version(l)
>>> l2
[3, 2, 1]

Note, however, that it also empties the original list:

>>> l1
[]

To avoid this, call e.g. l2 = while_version(l1[:]).

Upvotes: 1

Juan Fco. Roco
Juan Fco. Roco

Reputation: 1638

The trivial answer

Given

a = [1, 2, 3, 4, 5]

then

a[::-1]

returns

[5, 4, 3, 2, 1]

In your code:

  • You use r_list[(-a)+1], buy you have never assigned r_list any value (just "r_list = []")
  • I think your are confusing "items" with "r_list". So I think you want to return "r_list" instead of "items" (the input parameter)
  • The assignment should be "r_list[a] = items[-a-1]", but that doesn't work. You should use "r_list.append(items[-a-1])"
  • The return should be "return r_list"
  • "while (a!=b)" should be "while (a < b)" for readeability

Hope this helps

Upvotes: 0

Blue
Blue

Reputation: 557

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

Upvotes: 1

Related Questions