1

When generating list we do not use the builtin "list" to specify that it is a list just the "[]" would do it. But when the same style/pattern in used for tuple it does not.

 l = [x for x in range(8)]
print(l)

y= ((x for x in range(8)))
print(y)

Output:

[0, 1, 2, 3, 4, 5, 6, 7]
<generator object <genexpr> at 0x000001D1DB7696D0>

Process finished with exit code 0

When "tuple" is specified it displays it right. Question is:- In the code "list" is not explicitly mentioned but "tuple". Could you tell me why?

l = [x for x in range(8)]
print(l)

y= tuple((x for x in range(8)))
print(y)

Output:

[0, 1, 2, 3, 4, 5, 6, 7]
(0, 1, 2, 3, 4, 5, 6, 7)

Process finished with exit code 0
redpy
  • 143
  • 5
  • Take a look at https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python – Chris Aug 20 '21 at 06:09

1 Answers1

0

Using () is a generator expression:

>>> ((x for x in range(8)))
<generator object <genexpr> at 0x0000013FE1AD6040>
>>> 

As mentioned in the documentation:

Generator iterators are created by the yield keyword. The real difference between them and ordinary functions is that yield unlike return is both exit and entry point for the function’s body. That means, after each yield call not only the generator returns something but also remembers its state. Calling the next() method brings control back to the generator starting after the last executed yield statement. Each yield statement is executed only once, in the order it appears in the code. After all the yield statements have been executed iteration ends.

A generator in a class would be something like:

class Generator:
    def __init__(self, lst):
        self.lst = lst

    def __iter__(self):
        it = iter(self.lst)
        yield from it
        
    def __next__(self):
        it = iter(self.lst)
        return next(it)

Usage:

>>> x = Generator(i for i in range(5))
>>> next(x)
0
>>> next(x)
1
>>> next(x)
2
>>> for i in x:
    print(i)

3
4
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114