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()]))
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.
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.
Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.
Use the + operator The + operator can be used to concatenate two different strings.
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]
A simple way is:
def test():
for number in range(0,10):
yield number
yield number**2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With