1

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?

1
  • As a side note: Because [x][:-1] is legal (and returns an empty list), you could use an empty list as your base case instead of len(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). Commented Nov 27, 2013 at 19:14

1 Answer 1

3

with python builtin functions, if the function mutates the argument in place, by convention it returns None. So, since .insert mutates the list, it returns None.

Your idea is good, and I think the logic makes sense -- From an implementation standpoint, rather than using insert, you could use list concatenation:

def m_reverse(lst): if len(lst) == 1: return lst else: return [lst[-1]] + m_reverse(lst[:-1]) # return lst[-1:] + m_reverse(lst[:-1]) would also work. 
Sign up to request clarification or add additional context in comments.

10 Comments

any non-destruct functions that will do the same? something like lisps cons?
@elyashiv -- a developer can do whatever they want. I'm just saying what is conventional. There are a few notable exceptions. list.pop and dict.pop are two such exceptions.
@mgilson: The convention is that mutating methods don't return self, not that they don't return anything. Since pop has something useful to return (the popped value), it returns that. Since insert has nothing useful to return, it returns None.
@elyashiv: The reason Python doesn't come with functions like cons is that it would be misleading. A Python list is a variable length array, not a single-linked list. So, algorithms that repeatedly concatenate new items onto the front, which are the fastest way to do things in Lisp, are the slowest way to do things in Python.
@elyashiv -- For this example? use the builtin (reversed). Otherwise, the next best bet is to eliminate the recursion...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.