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.
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
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order = Anthony Mark Harry Jacob
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])
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order = Anthony Mark Harry Jacob
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)]
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order = Anthony Mark Harry Jacob
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]]
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!