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.
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 :-)
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With