I'm quite new to python, and as a exercise I wrote a simple reverse function.
the code:
def m_reverse(x): if len(x) == 1: return x return m_reverse(x[:-1]).insert(0,x[-1]) when I try it I get the following:
>>> m_reverse([1,2,3,4]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in m_reverse File "<stdin>", line 4, in m_reverse AttributeError: 'NoneType' object has no attribute 'insert' what's my mistake? Any critical data I'm lacking?
[x][:-1]is legal (and returns an empty list), you could use an empty list as your base case instead oflen(x) == 1. That would make your code a little simpler, and also make it work on empty lists instead of raising an exception. See here for an example (with mgilson's fix included).