how do you make a loop run in reverse?

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 26 21:08:45 EDT 2013


> On 27 March 2013 10:59, <rahulreddy24 at hotmail.com> wrote:
>>
>> So i have a set of for loops that create this :
>>
[snip]
>> but i want to nest all the loops under one BIG loop that'll run in reverse
>> to make this:
[snip]
>> Is this possible?

On 27 March 2013 00:19, Xavier Ho <contact at xavierho.com> wrote:
> There is a built-in function that reverses an iterable.  Have a look at the
> documentation.

I assume you mean the reversed function. It does not in general
reverse an iterable. From the docs:
"""
reversed(seq)

Return a reverse iterator. seq must be an object which has a
__reversed__() method or supports the sequence protocol (the __len__()
method and the __getitem__() method with integer arguments starting at
0).

New in version 2.4.

Changed in version 2.6: Added the possibility to write a custom
__reversed__() method.
"""

So it reverses a sequence (having the __len__ and __getitem__ methods)
or an object that advertises reversibility (having a __reversed__
method). It does not reverse anything else including generators,
iterators and most non-sequence iterables.

To the OP: To reverse a "set of for loops" as requested is not
possible using the reversed function. It is, however, possible to
reverse a list of strings. So if you have a function that returns the
list of strings you show as output then you can easily reverse that
list with reversed(mylist) or mylist[::-1].


Oscar



More information about the Python-list mailing list