Reverse a list in place!

We had our Hackbright graduation today. I have brand new red hoodie, which is awesome.
We also started doing whiteboard problems. Really easy ones, which help get over the fear.
Mine today was to reverse a list in place without using other functions like reverse in python. I could only use len to find the length of the list. (thank god right!)
I was almost done with it, when it was time for lunch. I was only missing the part about looping through half of the list only.
Came home tonight and figured it out in a few minutes.

def reverse_list(my_list): length = len(my_list)-1 temp=0 print "Reverse this list:",my_list for i in range(len(my_list)/2): first = my_list[i] last = my_list[length] temp = first my_list[i] = last my_list[length] = temp length -=1 print my_list return my_list reverse_list([1,2,4,5,6,7]) reverse_list([3,4,7,9,10,])

One thought on “Reverse a list in place!

  1. Cool! I was thinking about how to do this earlier in the week. This kind of gives me a good starting point for another code puzzle I was thinking about: a program to check if a word is a palindrome.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s