Reverse - getting strange results


#1

Hi,

I am not having much success with Reverse in Practice makes Perfect. Please would someone kindly help me understand why my code does not work. Currently it runs fine until I try to actually reverse. When I try and run on ‘abc’ it becomes ‘cbc’.

Most strangely, the tuple/‘holders_holder’ changes its charecters and i do not know why this is.

Many thanks in advance!

Here is my code:

def reverse(text):
  #make a holder list
    holder = []
    for i in range(0,len(text)):
        #standard itterate through and append. Making the text into a list
        holder.append(text[i])
    # make a dummy of the holder so that as 'holder' changes, the original list doesnt
    holders_holder = holder
    #holders_holder was not working and so i made it into an 'unmutable/changeable' tuple
    tuple(holders_holder)
    #check prints - everything is fine up to the end of the prints! here
    print (holders_holder)
    print (holder)
    print (len(holder))
    print (len(text))
    #two iteration variables...
    x = len(text)
    j = 0
    #while loop. We want to switch the first (0th) charecter of holder with the last in holders_holder
    #thus the j iterating up and the x iterating down
    # note that the index of holders_holder needs a -1 because otherwise the range would be outside
    #of the index (i.e. leng = 3 but iterations need to be 0, 1 ,2...
    while j < len(text):
        holder[j] = holders_holder[x-1]
        print (holder)
        print (holders_holder)
        j += 1
        x -= 1

reverse('abc')

#2
# make a dummy of the holder so that as 'holder' changes, the original list doesnt
    holders_holder = holder

what the comment describes, is not what is happening in reality.

both variables refer to the same list in memory. It sort of like given two friends (the two variables, holders_holder and holder) the address to your house (the list in memory). Changes to the house (list) will be seen by both your friends (the variables)


#3

Thanks so much. This makes so much sense, but I’ve spent a good bit of time and it seems to not be covered on any other forums etc.

I am still a bit baffled as to why a tuple can be changed. Everything I’ve read so far say that a tuple can not be changed.


#4

i have covered it on codecademy forum before, but its trying to find a needle in haystack

they can’t, but there isn’t a tuple in your code. You attempt to create a tuple here:

tuple(holders_holder)

but its not successful, given you do nothing with the returned result of the built-in tuple() function. Actually, if you had converted holders_holder to a tuple, you wouldn’t have the problem i described above (in my first reply)


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.