Iterating a list in reverse ?

Luis M. González luismgz at gmail.com
Wed Jun 21 13:26:08 EDT 2006


Andy Dingley <dingbat at codesmiths.com> wrote:
> Python newbie:  I've got this simple task working (in about ten
> different ways), but I'm looking for the "favoured" and "most Python
> like" way.
>
> Forwards I can do this
> for t in listOfThings:
>     print t
>
> Now how do I do it in reverse?   In particular, how might I do it if I
> only wanted to iterate part-way through (with a conditional test and a
> break), or if I had a large list ?
>
> reverse( listOfThings )
> for t in listOfThings:
>     print t


listOfThings = [1,2,3,4,5,6]

for i in listOfThings:
	print i                    # print from 1 to 6


 for i in listOfThings[::-1]:
	print i                     # prints from 6 to 1




More information about the Python-list mailing list