Generators can only yield ints?

Lie Lie.1296 at gmail.com
Sat Aug 23 11:24:42 EDT 2008


On Aug 23, 5:44 am, defn noob <circularf... at yahoo.se> wrote:
> def letters():
>         a = xrange(ord('a'), ord('z')+1)
>         B = xrange(ord('A'), ord('Z')+1)
>         while True:
>                 yield chr(a)
>                 yield chr(B)
>
> >>> l = letters()
> >>> l.next()
>
> Traceback (most recent call last):
>   File "<pyshell#225>", line 1, in <module>
>     l.next()
>   File "<pyshell#223>", line 5, in letters
>     yield chr(a)
> TypeError: an integer is required
>
>
>
> Any way to get around this?

The most direct translation on what you've done, with corrections, is
either this:

def letters():
    a = xrange(ord('a'), ord('z') + 1)
    B = xrange(ord('A'), ord('Z') + 1)
    while True:
        yield a
        yield B

>>> l = letters()
>>> l.next()
xrange(97, 123)

or this:

def letters():
    a = xrange(ord('a'), ord('z') + 1)
    B = xrange(ord('A'), ord('Z') + 1)
    while True:
        yield [chr(char) for char in a]
        yield [chr(char) for char in B]

>>> l = letters()
>>> l.next()
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

but my psychic ability guessed that you actually wanted this instead:


def letters():
    a = xrange(ord('a'), ord('z') + 1)
    B = xrange(ord('A'), ord('Z') + 1)
    a = [chr(char) for char in a]
    B = [chr(char) for char in B]
    index = 0
    while index < 26:
        yield a[index]
        yield B[index]
        index += 1

>>> l = letters()
>>> l.next()
'a'

or possibly in a more pythonic style, using for:

def letters():
    a = xrange(ord('a'), ord('z') + 1)
    B = xrange(ord('A'), ord('Z') + 1)
    for lower, upper in zip(a, B):
        yield chr(lower)
        yield chr(upper)

>>> l = letters()
>>> l.next()
'a'

paralelly, my psychic ability also tells me that you might prefer this
instead:

def letters():
    a = xrange(ord('a'), ord('z') + 1)
    B = xrange(ord('A'), ord('Z') + 1)
    for lower, upper in zip(a, B):
        yield chr(lower), chr(upper)

>>> l = letters()
>>> l.next()
('a', 'A')



More information about the Python-list mailing list