0

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
1
  • 3
    Make sure your indentation is correct, this is important in Python. It looks like the return items is indented, so it will happen the first time through the loop. Commented Feb 14, 2015 at 1:11

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

No problem, any time!
1

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[:]).

Comments

0

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

1 Comment

Thanks for the input! I fixed it earlier, but thanks for clearing up some stuff for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.