How to get a tuple from a generator? Best practice

I am a neophyte programmer, and I wanted to create a generator that will return two values ​​to me, which I will use in another function as a tuple.

I do not understand why it tuple(function_1(a,b))returns ((1, 2),), but tuple(function_2(a,b))will return the correct tuple.

It is interesting what happens here and what is the best syntax and in the end knows if a tuple can be obtained from function_1.

Thanks in advance for any explanation!

>>> def function_1(a,b):
...     yield a,b
...
>>> def function_2(a,b):
...     yield a
...     yield b
...
>>> a = 1
>>> b = 2
>>>
>>> function_1(a,b)
<generator object function_1 at 0x1007931b0>
>>> function_2(a,b)
<generator object function_2 at 0x1007931f8>
>>> tuple(function_1(a,b))
((1, 2),)
>>> tuple(function_2(a,b))
(1, 2)
>>> for item in function_1(a,b):
...    print(item)
...
(1, 2)
>>> for item in function_2(a,b):
...    print(item)
...
1
2
+4
source share
3 answers

Your first generator gives only once and gives a tuple:

>>> gen = function_1(1, 2)
>>> gen = function_1(1, 2)
>>> next(gen)
(1, 2)
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

next() ( - ), . StopIteration , .

, :

>>> gen = function_2(1, 2)
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

tuple() , , function_1 , . , . list() :

>>> list(function_1(1, 2))
[(1, 2)]
>>> list(function_2(1, 2))
[1, 2]

, - , , .

, . ; , , .

+6

, . Python , , , . , ,

def function_1(a,b):
    yield (a,b)

, , . .

0
>>> tuple((1,2))
(1, 2)

tuple , , .

>>> tuple(i for i in [(1, 2)])
((1, 2),)

, . , .

0

All Articles