0

While studying about Generator comprehension, I learned that they encloseds in (). Like:

G = (x**2 for x in range(4))

This will generate a Generator object which can either be used with G.__next__() or list(G)

On further reading, I found that other methods/functions that uses () are also generators. Example:

''.join(x.upper() for x in 'aaa,bbb,ccc'.split(','))


a,b,c = (x + '\n' for x in 'aaa,bbb'ccc'.split(','))

sum(x**2 for x in range(4))

etc..

before knowing about Generators, I used to think about these methods/functions to be 'normal methods'. I mean it seemed to me that they normally take arguments, process them and return. But now, they are referred to be 'Generator expressions' or whatever. So, does that mean that any expression that is enclosed in () is a generator expression? Does this make range() also a generator (I know it is not)? If not, then how can we distinguish?

Anurag Gupta
  • 31
  • 1
  • 6
  • 2
    It's the `for` in the middle that makes these generator expressions. – jasonharper Oct 04 '21 at 00:23
  • This question seems to be about the syntax of the language, and as such is better answered by a tutorial than on Stack Overflow. You could also try referring to the [documentation](https://docs.python.org/3/reference/expressions.html#generator-expressions), or the [original proposal](https://www.python.org/dev/peps/pep-0289/). – Karl Knechtel Oct 04 '21 at 00:26
  • There is no such thing as "generator comprehension". There is a generator expression - which is what you have in your first example, too - which *evaluates to* a generator object. You can *also* create a generator object by calling a function written with `yield` statements. The `()` are part of the syntax, but only incidentally - you can sometimes drop them *when you pass the generator directly to a function*, as in your `''.join` example. Things enclosed in `()` are **not** inherently generators - they can be *many* different kinds of things. – Karl Knechtel Oct 04 '21 at 00:30
  • You don't need to distinguish these things. What you need to know is if something is iterable, which you can establish by trying to iterate over it. (If for some reason you want to know before you use it, pass it to `iter()` and catch `TypeError`.) – kindall Oct 04 '21 at 00:49

0 Answers0