1

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]))
falsetru
  • 357,413
  • 63
  • 732
  • 636
whytheq
  • 34,466
  • 65
  • 172
  • 267

2 Answers2

4

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 :)

Community
  • 1
  • 1
jcdenton
  • 361
  • 2
  • 10
  • 1
    Thanks for extra points although not really addressing the question - to reverse the list recursively was simply a basic exercise in recursion - so using `reversed` misses the point. – whytheq Feb 24 '14 at 10:21
2

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Just to clarify, `list.append` appends to the list in place. `a = [1, 2, 3]; a.append(4); a == [1, 2, 3, 4];`. – rlms Feb 22 '14 at 17:37
  • @sweeneyrod, Thank you for comment. I added a mention about in-place append. – falsetru Feb 22 '14 at 17:41
  • @sweeneyrod the `==` does not check if append is inplace – zhangxaochen Feb 22 '14 at 17:41
  • @sweeneyrod That's not the real proof of the point that `append` is in place. More something like `a = b = [1, 2]; id(a) == id(b); a.append(3); id(a) == id(b)`. – Silas Ray Feb 22 '14 at 17:45
  • The `a == [1, 2, 3, 4]` was more just to show how `append` works, a shortcut for "and now `a` is `[1, 2, 3, 4]`". On another subject, why was this answer downvoted? – rlms Feb 22 '14 at 17:58
  • @downvoter: How can I improve the answer? I just wanted to let the OP why he/she got the unexpected result. I know there's better options like `reversed`, `seq[::-1]`, but it is already mentioned by jcdenton; I don't want to duplicate it. – falsetru Feb 22 '14 at 18:06