nick34992
2/12/2017 - 4:53 PM

Python Generator: Iterate Alphabet

Python Generator: Iterate Alphabet

#!/usr/bin/env python3.5

class LetterIter:
    def __init__(self, letters):
        '''Constructor'''
        self.letters = letters
        self.position = 0
    def __iter__(self):
        '''Returns self as iterator'''
        return self
    def __next__(self):
        '''if True, returns next letter;
        if False, raises StopIteration'''
        if self.position >= len(self.letters):
            raise StopIteration
        letter = self.letters[self.position]
        self.position += 1
        return letter

if __name__ == '__main__':  # standalone
    ltrs = LetterIter('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    for item in ltrs:
        print(item)