Reverse - trtying to debug code - don;t see why no worky


#1

i have a bunch of extra print statements, but i am trying to see the problem with indexing . i expect to be grabbing 3,2,1,0 from the lstr list, but output is:

['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
4
0 3 d
1 2 c
2 1 c
3 0 d

rlstr is ['d', 'c', 'c', 'd']

 def reverse(str):
    lstr= list(str)
    rlstr = lstr
    print lstr, rlstr
    length=len(lstr)
    print length
    for i in range(0, length):
        rlstr[i] = lstr[length-1-i]
        print i, length-1-i, lstr[length-1-i]  
    print "rlstr is", rlstr

    return rlstr
        
reverse('abcd')

#2

when you start, you have this list right:

['a','b','c','d']

now, we are going to do your loop for the first run, in which you say:

rlstr[i] = lstr[length-1-i]

now what this line does, is change the letter at index 0, to the letter at index 3 (index 0 = a, index 3 = d), so now you have:

['d','b','c','d']

then on the next run of your loop, you say. change the letter at index 1 (b) to the letter at index 2 (c), which will get you:

['d','c','c','d']

oops, this is not going right. You could add another print statement in your for loop: print rlstr

I recommend to append the letters to a new list in the process of reversing them.


#3

thanks, but i want to do exactly as you describe. (when you say oops it is doing exactly what i want) i want to change rlstr[0], then 1, then 2, then 3. the next iteration should change rlst[2] to lstr[1] , which is 'b.' i don;t see why this isn't happening.


#4

Oh wow, those are two different variables. well, the problem is, this:

rlstr = lstr

won't make a copy of a list, if you alter one of the lists now, both lists get altered. I recommend to read this


#5

sorry, it seems strange for a humble beginner like me to keep arguing with the moderator, but let me point out a couple things:
1. the print statement shows the content of both lists. it is line 4 of my code. (i accept your point about copying lists)
2. it shows the contents of the lists are identical.
3. i have print statements embedded in the for loop for debugging.
4. everything is working correctly until the line "2 1 c" appears. THIS is what I don't understand.

I know there are better ways to do this task, and i have done them. but i need to understand why this code doesn't do what i expect. Please take a careful look!
Much appreciated!!


#6

lets say we have this code:

rlstr = lstr
print lstr, rlstr

and we now add a line:

rlstr = lstr
lstr[0] = 'e'
print lstr, rlstr

you will see, both lists gets altered (because they are no copy, the point the same list). Combine this with what i explained above, and you should have your answer


#7

yes, i get it. it is like the old problems seen when dealing with reference vs. vale, etc. i see the stack overflow item.
thank you !!!!!!!!!!!