Please tell me how to approach the list from the back to the front

Asked 2 years ago, Updated 2 years ago, 88 views

array = [0,10,20,40] I'd like to approach from the back in order of 40->20->10->0.

In C++, for (i = array.length() - 1 ;i >= 0; i--) We wrote it together

While writing fori in list on Python, Is there a way to approach it from behind?

list python reverse

2022-09-21 19:27

1 Answers

array=[0,10,20,40]
for i in reversed(array):
    print i

The reversed() function returns list_reversiterator instead of list. If you want to do return, you must write list(reversed(array)).

This method uses the property that L[:-1] returns the list [40, 20, 10, 0] that has flipped L.

L = [0,10,20,40]
for i in L[::-1]:
    print i


2022-09-21 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.