NAstuden NAstuden - 2 months ago 21
Python Question

Reverse a list without using built-in functions

I'm using Python 3.5.

As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if

x = [a, b, c]
the function would make
x = [c, b, a]
.

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:

for revert in range(1, len(x) + 1):
y.append(x[-revert])


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

So I searched around and have made the following very simple code:

`y = x[::-1]`


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

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.

Jim Jim
Answer

range and len are both built-in functions. Since list methods are accepted, you could do this with insert. It is reeaallyy slow* but it does the job for small lists without using any built-ins:

def rev(l):
    r = []
    for i in l:
        r.insert(0, i)
    return r

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

>>> print(rev([1, 2, 3, 4]))
[4, 3, 2, 1]

Doing:

def rev(l): 
    return l[::-1] 

could also be considered a solution. ::-1 (:: has a different result) isn't a function (it's a slice) and [] is, again, a list method. Also, contrasting insert, 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 in this S.O answer.

*Reeaaalllyyyy slow, see juanpa.arrivillaga's answer for cool graph

Comments