Python Tutorial

Sunday, October 7, 2012

Python design pattern : Iterator


Iterators are built into the Python language. Dictionaries, lists, tuples, strings, streams, generators, and classes for which you implement iterator syntax are iterable. Lets see an example of iterator pattern with generator.

 
def show_chars(n):
    list=['A','B','C','D','E','F','G','H','I','J']
    for data, pos in zip(list, range(n)):
        yield data

chars_set= show_chars(5)
for ch in chars_set:
    print ch


Output:
A
B
C
D
E

0 comments:

Post a Comment