Skip to content
Home » How to Loop over a Sequence in Reverse

How to Loop over a Sequence in Reverse

Spread the love

You may sometimes need to loop over a sequence in reverse. To this end you can use the reversed function. Here’s a list of planets. We’re going to print all the elements of the list in their original order and then in reversed order:

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
print("Planets from nearest to farthest from the Sun:")

for planet in planets:
    print(planet)

print()
print("Planets from farthest to nearest from the Sun:")

for planet in reversed(planets):
    print(planet)

Here’s the result:

Planets from nearest to farthest from the Sun:
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune

Planets from farthest to nearest from the Sun:
Neptune
Uranus
Saturn
Jupiter
Mars
Earth
Venus
Mercury

As you can see, it’s pretty simple and straightforward.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply