Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse a list in reverse order in Python (index-style: '... in range(...)' only)

I'm new to Python so I am still getting used to looping in this language. So, for example, I have the following code (the element type in the list is array)

my_list = [array0, array1, array2, array3]
temp = my_list[-1]
for k in range(len(my_list) - 1, 0):
    temp = temp + my_list[k - 1]
return temp

I want to traverse the list from the end of the list and stop at the second element (k=1), but it looks like the for loop will never be entered and it will just return the initial temp outside the loop. I don't know why. Can someone help? Thanks.

like image 586
mengmengxyz Avatar asked Oct 31 '25 10:10

mengmengxyz


2 Answers

Avoid looping with range, just iterate with a for loop as a general advice.

If you want to reverse a list, use reversed(my_list).

So in your case the solution would be:

my_list = reversed([array0,array1,array2,array3])

That gives you [array3, array2, ...]

For omitting the last array from the reversed list, use slicing:

my_list = reversed([array0,array1,array2,array3])[:-1]

So your code turns to a one liner :-)

like image 51
jazz Avatar answered Nov 03 '25 00:11

jazz


You can traverse a list in reverse like so:

for i in range(len(lis), 0, -1):
    print (i)

To stop at the second element edit your range() function to stop at 1:

for i in range(len(lis), 1, -1):
        print (i)
like image 40
Hassan.S Avatar answered Nov 02 '25 22:11

Hassan.S