9

How can I concatenate two items when yielding from a function in python?

The base case:

import itertools

def test():
    for number in range(0,10):
        yield number

list(test()) # [0...9]

What if I want to yield both the number and its square number**2

import itertools

def test():
    for number in range(0,10):
        yield itertools.chain.from_iterable([
            number,number*2
        ])

list(test()) 

# [0,0,1,1,2,4,3,9,...] pretended
# <itertools.chain at 0x135decfd0> ... what I got

However doing itertools.chain.from_iterable([generator1, generator2]) from the outside gives the expected result.

def first_list():
    for number in range(0,5):
        yield number

def second_list():
    for number in range(5,10):
        yield number

list(itertools.chain.from_iterable([first_list(), second_list()]))
3
  • 11
    Why not simply: yield number <newline> yield number**2?
    – vaultah
    May 10, 2017 at 22:07
  • You don't want to concatenate, you want a double yield ... that's a difference.
    – Paebbels
    May 10, 2017 at 23:25
  • from the outside they come out concatenated May 10, 2017 at 23:31

2 Answers 2

11

Python 3.3 also introduced the yield from (see also PEP-380) syntax which allows you to do something like this:

>>> def test():
...   for number in range(10):
...     yield from (number, number**2)
...
>>> list(test())
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]
0
10

A simple way is:

def test():
    for number in range(0,10):
        yield number 
        yield number**2
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.