Generators, iterators

An itorator is a thing like an array, that you can go over one bit at a time in order, except the thing doesn't necesarily have to exist.

# a generator 

def counter(n=0):
    while True:
        n += 1
        if n > 100:
           return
        yield n
    
c = counter(5)
    
for x in c: print x
# 6
# 7
# ...
# 100

Sequences (lists, strings, tuples), file objects, dictionaries, generators, are all iterables. It is easy to make an object behave as an iterator by defining __iter__ and next methods.

for letter in 'elephant':
    print letter.join('loaf')
#leoeaef
#llolalf
#leoeaef   

They provide a nifty interface between different seuqences, and can save al ot of memory if the whole sequence isn't all needed at once.