whytheq
whytheq

Reputation: 35557

Simple function to reverse a list

Using the + operator works fine. If I try to write using the append method it returns None.

Can revFromEnd2 reverse the list using the append method?

def revFromEnd(L):
    if len(L)==1:
        return L
    else:
        return [L[-1]] + revFromEnd(L[:-1])

def revFromEnd2(L):
    if len(L)==1:
        return L
    else:
        return [L[-1]].append(revFromEnd2(L[:-1]))

print(revFromEnd([1,2,3,4,5]))
print()
print(revFromEnd2([1,2,3,4,5]))

Upvotes: 1

Views: 127

Answers (2)

jcdenton
jcdenton

Reputation: 361

There is a built-in function reversed:

>>> l = [1, 2, 3]
>>> list(reversed(l))
[3, 2, 1]

You could also use slices (their syntax is [start:end:step], so if you define a negative value for step, it would make a slice in opposite direction):

>>> l = [1, 2, 3]
>>> l[::-1]
[3, 2, 1]

UPD: Yes, recursion is great, but since you're using Python and it doesn't optimize tail recursion, it'd be better to use more obvious methods :)

Upvotes: 4

falsetru
falsetru

Reputation: 368924

list.append appends an item to the list in place and returns nothing (= return None), unlike + operator which return new list concatenating two lists:

>>> [1, 2] + [3]
[1, 2, 3]
>>> [1, 2].append(3) # => None
>>>

BTW, you'd better use list.extend considering that recvFromEnd1/2 return list:

>>> lst = [1,2]
>>> lst.append([3,4])
>>> lst
[1, 2, [3, 4]] # <--- Is this what you want?


>>> lst = [1,2]
>>> lst.extend([3,4])
>>> lst
[1, 2, 3, 4]

def revFromEnd2(L):
    if len(L)==1:
        return L
    else:
        ret = [L[-1]]
        ret.extend(revFromEnd2(L[:-1]))
        return ret

Upvotes: 2

Related Questions