1

I am a student in an intro-level python class, and my task is to define "reverse(mylist)" using while loop

This is what I have so far:

def reverse(mylist):
    a=0
    b=len(mylist)
    xlist=mylist
    while(a!=b):
        mylist[a]=xlist[(-a)-1]
        a+=1
    return mylist

Let's say the input list is [1,2,3,4,5,6], and using my reverse function I will get the output [6, 5, 4, 4, 5, 6]... And [1,2,3,4,5] will become [5,4,3,4,5]

I am not sure what I am doing wrong here.

1
  • 1
    Could you fix your indentation? Commented Feb 24, 2014 at 8:33

2 Answers 2

2

Following statement makes both xlist, mylist reference same list object:

xlist = mylist

You need to copy it.

xlist = mylist[:]

BTW, using for loop, you don't need to increment a manually:

for a in range(len(mylist)):
    ....
Sign up to request clarification or add additional context in comments.

Comments

0
def reverse(mylist):
  a=0
  b=len(mylist)
  xlist=[]
  while(a!=b):
    mylist[a:a]=xlist[(-a)-1]
    a+=1
  return mylist

list is transfered by referance not by value. you need to create new list. "xlist = mylist" only create a referance.

ps "for in" is more commonly used in python.

for i in range(2, -1, -1):
  xlist.append(mylist[i])

or:

xlist = [mylist[i], for i in range(2, -1, -1) ]

Comments

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.