1336

How do I iterate over a list in reverse in Python?


See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?

2
  • From what I can tell, the question was only ever intended to be about iteration. However, the day after it was asked, someone tried to fix the (rather poor) title - and misunderstood, giving it the title "How to reverse a list?" (which means changing around the order of the elements, not looking at the elements in a different order). The question then attracted answers for both problems, so now we have a rather confused canonical. I at least added to the title to indicate that both purposes are served here. Aug 11, 2022 at 8:15

37 Answers 37

1
2
0

use

print(list(reversed(list_name)))
2
  • 1
    <list_reverseiterator object at 0x0000021C517D3DA0> Nov 19, 2020 at 13:45
  • This output is unreadable... Use print(list(reversed(list_name))) instead. Dec 21, 2020 at 16:10
-1
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 1]
-1

This class uses Python magic methods and iterators for reversing, and reverses a list:

class Reverse(object):
    """ Builds a reverse method using magic methods """

    def __init__(self, data):
        self.data = data
        self.index = len(data)


    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration

        self.index = self.index - 1
        return self.data[self.index]


REV_INSTANCE = Reverse([0, 10, 20, 40])

iter(REV_INSTANCE)

rev_list = []
for i in REV_INSTANCE:
    rev_list.append(i)

print(rev_list)  

Output

[40, 20, 10, 0]
-1

A clean simple class object to solve your issue.

class lister():
    def reverse(self):
        return  [self[len(self)-e]for e,x in enumerate(self,start=1)]
print(lister.reverse([0, 10, 20, 40]))
-1

alternative way using list comprehension and abs

array = [0, 10, 20, 40]

reversed_array = [array[abs(indx)] for indx in range(abs(len(array)-1),1)]
            
reversed_array
[40, 20, 10, 0]
-1
The cute Solution


class List_reverse():
    def reverse_list(self):
        list = [1, 2, 3, 4, 5, 6]
        list1 = []
        for i in range(1, len(list)+1):
            list1.append(list[-i])
        print(list1)


if __name__ == "__main__":
    obj = List_reverse()
    obj.reverse_list()
    enter code here
1
  • 1
    What makes this "cute", and how is it better than the 50 or so existing answers? Please read How to Answer, and please make sure to explain the code you share.
    – Chris
    May 19, 2022 at 1:38
-2

I had this question come up during a python code test for a job interview. The below is my answer. Note it works for any value any length

def get_reverse(list_check, count_num):
    final_list =[]
    for index in range(list_length):
        value = list_check[count_num]
        final_list.append(value)
        count_num = count_num -1

    return final_list

new_list = ['A', 'GOAT', 'C', 'D', 'Mac']

list_length = len(new_list)
x = list_length -1

print(get_reverse(new_list, x))
1
  • There there are several points that make your function more complicated and un-pythonic than necessary – but there's a fatal error: list_length, which is used inside the function, exists only as a global variable. That's why I'll downvote this answer (but I'll retract the DV if you fix that).
    – Schmuddi
    Jul 7, 2021 at 11:49
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.