You're doing a lot of funky things, including trying to assign to a list by a higher index and assuming it will "Fill in the blanks" as it were.
In [1]: x = []
In [2]: x[4] = 1
# what you want to happen:
# x = [None, None, None, None, 1]
# what actually happens:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-2-a9f6d07b2ba4> in <module>()
----> 1 x[4] = 1
IndexError: list assignment index out of range
So let's take a different approach instead. What you really want to do is to take every character of the string and put them in the opposite order. Well lists have a pop
method that removes and returns the last element, and an append
element that adds to the end. That sounds about right. Luckily it's also really easy to turn a string into a list!
In [3]: s = "abcd"
In [4]: list(s)
Out[4]: ['a', 'b', 'c', 'd']
Now let's iterate through, pop
ing and append
ing as we go, once per element in the new list.
In [5]: def new_reverse(s):
...: in_ = list(s)
...: out = []
...: for _ in range(len(in_)):
...: ch = in_.pop()
...: out.append(s)
...: return out
...:
In [6]: new_reverse("abcd")
Out[6]: ['d','c','b','a']
Well now we turned our string into a reversed list. That's the hard part, because joining lists back together into strings is really elementary. str
has a join
method that takes an iteratable and joins all the elements with the str
calling it, e.g.
'|'.join(['a','b','c','d']) --> 'a|b|c|d'
'/'.join(['', 'usr', 'bin']) --> '/usr/bin'
If you use an empty string, ''
, this should all glob back together like normal.
In [12]: def new_reverse(s):
...: in_ = list(s)
...: out = []
...: for _ in range(len(in_)):
...: ch = in_.pop()
...: out.append(s)
...: return ''.join(out)
...:
In [13]: new_reverse('abcd')
Out[13]: 'dcba'