How do I iterate over a list in reverse in Python?
-
Possible duplicate of stackoverflow.com/questions/931092/reverse-a-string-in-python– ᴇɴᴅᴇʀᴍᴀɴJun 24, 2022 at 22:24
-
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.– Karl KnechtelAug 11, 2022 at 8:15
37 Answers
use
print(list(reversed(list_name)))
-
1
-
This output is unreadable... Use
print(list(reversed(list_name)))
instead. Dec 21, 2020 at 16:10
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 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]
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]))
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]
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
-
1What 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.– ChrisMay 19, 2022 at 1:38
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))
-
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).– SchmuddiJul 7, 2021 at 11:49