Reverse a list without using built-in functions
<p>I'm using Python 3.5. </p>

<p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p>

<p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p>

<pre><code>for revert in range(1, len(x) + 1):
    y.append(x[-revert])
</code></pre>

<p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p>

<p>So I searched around and have made the following very simple code:</p>

<pre><code>y = x[::-1]
</code></pre>

<p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p>

<p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>

<p><code>range</code> and <code>len</code> are both <a href="https://docs.python.org/3/library/functions.html" rel="nofollow">built-in functions</a>. Since <code>list</code> <em>methods</em> are accepted, you could do this with <a href="https://docs.python.org/3.5/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>insert</code></a>. It is <em>reeaallyy slow</em><sup>*</sup> but it does the job for <em>small</em> lists without using any built-ins:</p>

<pre><code>def rev(l):
    r = []
    for i in l:
        r.insert(0, i)
    return r
</code></pre>

<p>By continuously inserting at the zero-th position you end up with a reversed version of the input list:</p>

<pre><code>&gt;&gt;&gt; print(rev([1, 2, 3, 4]))
[4, 3, 2, 1]
</code></pre>

<p>Doing:</p>

<pre><code>def rev(l): 
    return l[::-1] 
</code></pre>

<p>could also be considered a solution. <code>::-1</code> (<code>::</code> has a different result) isn't a function (it's a slice) and <code>[]</code> is, again, a list method. Also, contrasting <code>insert</code>, it is faster and way more readable; just make sure you're able to understand and explain it. A nice explanation of how it works can be found <em><a href="http://stackoverflow.com/questions/766141/reverse-a-string-in-python?lq=1">in this S.O answer.</a></em></p>

<p><sup>*Reeaaalllyyyy slow, see juanpa.arrivillaga's answer for cool plot and <code>append</code> with <code>pop</code> and take a look at in-place <code>reverse</code> on lists as done in Yoav Glazner's answer.</sup></p>

python list python-3.x