Skip to content

Instantly share code, notes, and snippets.

@mskeving
Created April 10, 2015 19:23
Show Gist options
  • Save mskeving/98309363925a1b33d5f5 to your computer and use it in GitHub Desktop.
Save mskeving/98309363925a1b33d5f5 to your computer and use it in GitHub Desktop.
Reverse a list in python
# Note, these functions are only for reversing lists in Python.
# In Python, strings are immutable, meaning you can't change their value.
# In other languages, like Ruby, this would be possible.
# If you want to reverse a string, you can use .split(), but that
# returns a list of characters, which means you are no longer doing
# it in place. This gives you O(n) space complexity.
# O(n) space, because the new list could be arbitrarily large
# O(n) time to go through each item in list.
def reverse_list(l):
reversed_list = l[::-1]
return reversed_list
# O(1) space complexity because no extra data structure is needed
# O(n) time complexity because it depends on the length of the list.
def reverse_list_in_place(l):
for i in xrange(len(l)/2):
beginning = i
end = -i-1
temp = l[end]
l[end] = l[beginning]
l[beginning] = temp
return l
# This reverses a list in place, but doesn't require a temp holder, so a bit cleaner
# It's still O(1) space complexity
# and O(n) time complexity
def reverse_list_with_fewer_lines(l):
for i in xrange(len(l)/2):
beginning = i
end = -i-1
l[beginning], l[end] = l[end], l[beginning]
return l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment