Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate while yielding

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()]))
like image 412
raul ferreira Avatar asked May 10 '17 22:05

raul ferreira


People also ask

How do you concatenate 3 strings in Python?

To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

What is the best way to concatenate strings in Python?

One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.

How do you concatenate text in Python?

Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

How do you concatenate two strings in Python?

Use the + operator The + operator can be used to concatenate two different strings.


2 Answers

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]
like image 158
MSeifert Avatar answered Oct 10 '22 16:10

MSeifert


A simple way is:

def test():
    for number in range(0,10):
        yield number 
        yield number**2
like image 43
carlos rodrigues Avatar answered Oct 10 '22 16:10

carlos rodrigues