Skip to content Skip to sidebar Skip to footer

Iterating An Interable Sequence In Reverse Order

I have a iterable sequence nums = [1,2,3,4]. I want to create a generator function which, when next(nums) is used, will return the values one by one in reverse order. My goal is to

Solution 1:

>>> def solution(lst):
...     dex = len(lst) - 1
...     while dex >= 0:
...         yield lst[dex]
...         dex -= 1
... 
>>> nums = solution([1, 2, 3, 4])
>>> next(nums)
4
>>> next(nums)
3
>>> next(nums)
2
>>> next(nums)
1
>>> next(nums)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

Post a Comment for "Iterating An Interable Sequence In Reverse Order"