Issue
How do I iterate over a list in reverse in Python?
Solution
To get a new reversed list, apply the reversed
function and collect the items into a list
:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
Answered By - codaddict
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.