I'm kind of confused over the iterator object/concept and the yield statement and its usage.

According to my understanding, all the python sequence are iterators, as they don't need the classic for (int i=0; i<list.length; i++) to iterate through lists/arrays.

Am I correct over this? Am I missing anything?

Also how would i use the yield statement? (not getting it from the official explanation)

Recommended Answers

All 4 Replies

I'm kind of confused over the iterator object/concept and the yield statement and its usage.

According to my understanding, all the python sequence are iterators, as they don't need the classic for (int i=0; i<list.length; i++) to iterate through lists/arrays.

Am I correct over this? Am I missing anything?

Also how would i use the yield statement? (not getting it from the official explanation)

Java... to iterate through list/arrays you can still do

for (type var : arr) {
    body-of-loop
}

I think you mean "generators" in Python.

So you have

def my_gen():
    yield 1
    yield "hello"
    yield "world"
    yield 100

for x in my_gen():
    print x

Generator is function which 'freezes' for every result and yields it, when next answer is requested function is 'unfrozen' with all the local state. When all answers are finished the iterator gives StopIteration exception and does not give more results.

Sequences that are iterable have method called __iter__ and that is called when they are used as iterators. So this is equivalent to normal iteration of list:

for i in iter(['a','b','c']): print i

iter makes iterator explicitly.

More info on the __iter__ method:

class Alphabet(object):
    def __iter__(self):  #This is the __iter__ magic method
        for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            yield letter

myalph = Alphabet()

for l in myalph:
    print l


class WeirdList(list):
    def __init__(self, *args, **kwargs):
        if args:
            self._l = args[0]
        super(WeirdList, self).__init__(*args,**kwargs)
    def __iter__(self):
        for x in self._l[::2]:
            yield x

myweirdlist = WeirdList((1,2,3,4,5,6,7,8,9))
for x in myweirdlist:
    print x

ah that makes a lot of sense. thanks jcao

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.