[Tutor] question about the build-in function reversed in Python2.5

Steven D'Aprano steve at pearwood.info
Sun Dec 25 14:40:11 CET 2011


daedae11 wrote:
> The build-in function reversed() in Python2.5  returns a iterator. But I don't know how to use the iterator.
> Please give me a simple example about how to use bulid-in function reversed() to reverse a list.

You use the iterator the same way you would any other iterator:

* in for loops:

     for obj in reversed(my_list):
         print(obj)

* pass it to functions which expect an iterator:

     a = reduce(function, reversed(my_list))
     b = map(func, reversed(my_string))

* create a new sequence:

     my_list = list(reversed(my_list))


Note that the advantage of reversed is that it is lazy (it returns an 
iterator). If you just want a copy of a list in reverse order, you can use 
slicing:

     my_list[::-1]

(also works on strings and tuples).

If you want to reverse the list in place, instead of making a copy:

     my_list.reverse()  # must be a list, not strings or tuples


reversed() is more general: it can work on any finite iterable object, not 
just lists.




-- 
Steven



More information about the Tutor mailing list