1

I'm doing this in attempt to better understand the iter() and next() methods better.

So I understand this can easily be done like this using some built-ins:

>>>animal = 'cat'
>>>print(list(reversed(animal)))
['t','a','c']

But this can also be done creating a class iterable:

class Reverselist():
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index =self.index -1
        return self.data[self.index]

    def intolist(self):
        self.test = [i for i in self]
        return self.test

rev = Reverselist('cat')
print(rev.intolist())

['t','a','c']

However, I'm having some trouble doing the same thing but using functions instead of going the OOO route.

Is there a way to do this with functions using iter() and next() methods without having to resort to comprehensions and loops?

2
  • 2
    What exactly do you mean by "using functions"? It should be easy your own reverse list iterator as a generator function, but you'll need at least one loop of some kind (either while index > 0 or a for index in range(len(lst)-1,-1,-1)). Commented Nov 1, 2015 at 18:30
  • 1
    Don't confuse iterators and iterables. An iterator doesn't necessarily have to generate a finite sequence, and so doesn't have a last element to start with. Commented Nov 1, 2015 at 18:43

1 Answer 1

1

You can do this with a generator function:

def reverse_list(seq):
    for index in range(len(seq)-1, -1, -1):
        yield seq[index]

Calling this function will produce a "generator object" that supports iter() and next().

>>> rev = reverse_list('cat')
>>> rev
<generator object reverse_list at 0x10a93ebe0>
>>> next(rev)
't'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I was more looking for a way to do this using iter()and next() explicitly? I understand that makes it more difficult than it should be.
@bLunt If you want to specify the behavior of iter() and next() explicitly, then use your original approach of defining an object with __iter__ and __next__ methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.