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)):
....
Question
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.
Solution
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)):
....
OTHER TIPS
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) ]