Python list loop reverse

Python : Different ways to Iterate over a List in Reverse Order

In this article we will discuss different ways to Iterate over a python list in reverse order.

Suppose we have a python list of strings i.e.

# List of string wordList = ['hi', 'hello', 'this', 'that', 'is', 'of']

Now we want to iterate over this list in reverse order( from end to start ) i.e.

We don’t want to change the order in existing list, just want to iterate in reverse. Now let’s see how to do this using different techniques,

Frequently Asked:

Iterate over the list in reverse using while loop

Get the size of list and using random and use random access operator [] to access elements in reverse i.e. from (size-1) to 0.

''' Iterate over the list in reverse using while loop ''' # Point i to the last element in list i = len(wordList) - 1 # Iterate till 1st element and keep on decrementing i while i >= 0 : print(wordList[i]) i -= 1

Iterate over the list in reverse using for loop and range()

Suppose if wordList had n elements then,

Читайте также:  Классы

For example, wordList had 5 elements then above specified range() function will return,

Now use that range() function in for loop and use random access operator [] to access elements in reverse i.e.

''' Iterate over the list using for loop and range() ''' for i in range( len(wordList) - 1, -1, -1) : print(wordList[i])

Iterate over the list using for loop and reversed()

reversed() function returns an iterator to accesses the given list in the reverse order.

Let’s iterate over that reversed sequence using for loop i.e.

''' Iterate over the list using for loop and reversed() ''' for i in reversed(wordList) : print(i)

It will print the wordList in reversed order.

Iterate over the list using List Comprehension and [::-1]

It will create a temporary revesed list

Let’s use this in List comprehension to iterating over the list in reverse i.e.

''' Iterate over the list using List Comprehension and [::-1] ''' [print (i) for i in wordList[::-1]]

Iterate over the list using List Comprehension and reversed()

''' Iterate over the list using List Comprehension and [::-1] ''' [print (i) for i in reversed(wordList)]

Complete example is as follows,

""" Different ways to Iterate over a list in reverse Order """ def main(): # List of string wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] #print the List print(wordList) ''' Iterate over the list in reverse using while loop ''' # Point i to the last element in list i = len(wordList) - 1 # Iterate till 1st element and keep on decrementing i while i >= 0 : print(wordList[i]) i -= 1 print("*************") ''' Iterate over the list using for loop and range() ''' for i in range( len(wordList) - 1, -1, -1) : print(wordList[i]) print("*************") ''' Iterate over the list using for loop and reversed() ''' for i in reversed(wordList) : print(i) print("*************") ''' Iterate over the list using List Comprehension and [::-1] ''' [print (i) for i in wordList[::-1]] print("*************") ''' Iterate over the list using List Comprehension and [::-1] ''' [print (i) for i in reversed(wordList)] if __name__ == "__main__": main()
['hi', 'hello', 'this', 'that', 'is', 'of'] of is that this hello hi ************* of is that this hello hi ************* of is that this hello hi ************* of is that this hello hi ************* of is that this hello hi

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Reverse for loop Python

In this tutorial, you will learn how to use for loop in reverse order in Python.

In python, for loop is used to iterate over a sequence (list, tuple, string) or other iterable objects. By default, the for loop iterates over the sequence in ascending order. Means it starts from the first element and ends at the last element.

However, you can also iterate over a sequence in reverse order. Starting from the last element and ending at the first element.

reverse for loop python

There can be multiple different approaches to iterate over a sequence in reverse order. Let’s see them one by one.

1. Using reversed() function

The reversed() function returns a reverse iterator which can be used to iterate over a sequence in reverse order.

Here is an example of how to use reversed() function in for loop.

my_list = [1, 2, 3, 4, 5] # Iterate over the elements of the list in reverse order for element in reversed(my_list): print(element)

Here, we have created a list of numbers. Then we used reversed() function to iterate over the elements of the list in reverse order.

Note the original list is not modified by the reversed() function.

2. Reverse loop using negative step

Another way to create a reverse loop in Python is to use the built-in range() function with a negative step value.

For example range(5, 0, -1) will return a list of numbers from 5 to 1 in reverse order.

# reverse for loop for i in range(5, 0, -1): print(i)

Here, the range() function starts at 5 and ends at 1. The step value is -1. So, effectively it iterates over the sequence in reverse order.

Another way of reversing the loop with a negative step is by using the len() function within the range() function as follows.

my_list = [1, 2, 3, 4, 5] # Iterate over the elements of the list in reverse order for i in range(len(my_list)-1, -1, -1): print(my_list[i])

Here, we have used len() function to get the length of the list. Then we used the length of the list as the starting point of the range() function. The step value is -1. So, effectively it iterates over the sequence in reverse order.

This is all about for loop in reverse order in python. Hope you have learned something new today.

Источник

Оцените статью