Right now I do it like this:
for i in range(len(my_list)-1, -1, -1):
# ...
but I am wondering if we have a better way with clearer meaning.
Use the reversed()
function :
for elem in reversed(my_list):
An object can support efficient reverse iteration by offering a __reversed__()
special method ; list objects implement this method to support reverse iteration efficiently. Otherwise, the normal sequence protocol ( object.__getitem__()
and object.__len__()
) must be implemented.
Note that this doesn't create a new list object; it produces an iterator , an object that tracks position in the list as you loop over it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.