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.
Here’s the video version:
Spread the love