Home >Backend Development >Python Tutorial >How to iterate a sequence in reverse order in Python?

How to iterate a sequence in reverse order in Python?

WBOY
WBOYforward
2023-08-25 20:57:10765browse

How to iterate a sequence in reverse order in Python?

Python sequences include strings, lists, tuples, etc. We can combine elements of Python sequences in different ways. Let's look at some examples of iterating a list in reverse order.

Use a while loop to iterate in reverse order

Example

In this example we have a list as a sequence and use a while loop to iterate in reverse order -

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Length - 1
i = len(mylist) - 1

# Iterate in reverse order
print("Display the List in Reverse order = ")
while i >= 0 :
   print(mylist[i])
   i -= 1

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

Use a for loop to iterate in reverse order

Example

In this example we have a list as a sequence and use a for loop to iterate in reverse order -

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order
print("Display the List in Reverse order = ")
for i in range(len(mylist) - 1, -1, -1):
   print(mylist[i])

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

Use reverse() to iterate in reverse order

Example

In this example, we have a List as a sequence and use the reversed() method to iterate in reverse order -

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order using reversed()
print("Display the List in Reverse order = ")
[print (i) for i in reversed(mylist)]

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

Use negative indexes for reverse iteration

Example

In this example, we take the List as a sequence and use negative indexes to iterate over it in reverse order

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order using negative indexing
print("Display the List in Reverse order = ")
[print (i) for i in mylist[::-1]]

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

The above is the detailed content of How to iterate a sequence in reverse order in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete