# How reverse a list with Sage?

From the section "Modifying lists: reverse, sort, ...":

L = [4,2,5,1,3]

L.reverse()

sage: [3, 1, 5, 2, 4]

However I see -- nothing.

print L.reverse()

gives 'None'. I am using Sage 5.8.

edit retag close merge delete

Sort by ยป oldest newest most voted

The method .reverse() reverses the list L on place (it modifies the list L as stated in the tutorial), it does not return a reversed copy of L (it returns nothing, hence your behaviour), but the list L itself is modified as you can check:

sage: L = [4,2,5,1,3]
sage: L.reverse()
sage: L
[3, 1, 5, 2, 4]


Now if you want to get a reversed copy of L without modifying L, you can use the reversed() function:

sage: L = [4,2,5,1,3]
sage: L2 = reversed(L)
sage: L2
<listreverseiterator at 0x65a5d50>


As you can see, it returns an iterator, not a list, it means that you can still play with it as if it was a list, but only once (the elements of L2 are thrown once used):

sage: for i in L2:
....:     print i
....:
3
1
5
2
4
sage: for i in L2:
....:     print i
....:
<nothing printed>


If you want to get a reversed list of L without modifying L you can transform the reversed iterator into a list:

sage: L = [4,2,5,1,3]
sage: L2 = list(reversed(L))
sage: L2
[3, 1, 5, 2, 4]

more

Thanks! Somehow I am used to assume that L.reverse() returns the reversed L. Am I the only one who finds this behaviour more natural?

( 2013-08-02 07:31:14 +0200 )edit

I think it is about english language: reverse reverses the list reversED returns the reversed list. As for me, the main "issue" is that reversed() is a function, not a method, which you can not guess by tab completion. By the way, both features are Python (not Sage) builtins.

( 2013-08-02 08:30:42 +0200 )edit

To complement Thierry's answer, here is another way to get a reversed list:

sage: L = [4,2,5,1,3]
sage: L[::-1]
[3, 1, 5, 2, 4]


This produces a new list. The original list is unchanged.

more

1

Thanks Samuel. And to complement it, is seems that reversed(L) is faster than L[::-1] which is faster than list(reversed(L)).

( 2013-08-02 08:32:07 +0200 )edit

"it seems that reversed(L) is faster.." Of course, because it just returns a pointer to a function but does reverse anything. I am still very unhappy with this counterintuitive parlance which is also not in accordance with English language.

( 2013-08-03 05:47:04 +0200 )edit