Indentation
I get a syntax error on my version of Python due to the indentation of these lines:
if len(left) > 0: i = left[0] else: i = None
I had to move them one space to the left to fix the error. Perhaps your version of Python is more forgiving, or perhaps there was a problem when you pasted the code into the question.
Naming
sort
is the name of a built-in list method. It would be better to rename your function:
def sort(lst):
to something like:
def merge_sort(lst):
It is common to use a plural noun for an array variable name. For example, lst
could be items
, or something more specific to this application.
The same applies to the arguments of the merge
function
left,right
Since they are arrays:
lefts, rights
In the sort
function, this expression is repeated a few times:
len(lst)
You could set that to a variable:
number = len(lst)
The code would be a little simpler and perhaps a little more efficient.
Simpler
For this line:
if len(left) > 0:
there is no need for the comparison. This is simpler:
if len(left):
There is no need for this for
loop:
for i in l_rest: out.append(i)
You could simply use the extend
list method:
out.extend(l_rest)
The same is true for this loop:
for i in right:
Or, as seen in the previous answer, +
can also be used.
Documentation
The PEP 8 style guide recommends adding docstrings for functions. The docsrting should summarize what the function does, and it should describe the input types and return type. It should mention that the sort
function is recursive.
out += l_rest + right
instead offor i in l_rest: out.append(i); for i in right: out.append(i)
\$\endgroup\$