[Tutor] Python Generator expressions
Steven D'Aprano
steve at pearwood.info
Tue Jul 23 21:22:34 EDT 2019
On Wed, Jul 24, 2019 at 11:26:26AM +1200, David L Neil wrote:
> Clarifying the difference/similarity in appearance between a generator
> expression and a tuple, it might help to think that it is the comma(s)
> which make it a tuple!
David makes an excellent point here. Except for the special case of the
empty tuple, it is *commas* that create tuples, not parentheses. The
round brackets are used for grouping, and are optional:
py> a = 1, 2, 3
py> type(a)
<class 'tuple'>
The only times you *need* parens around a non-empty tuple is to group
the items or to avoid ambiguity, e.g. a tuple inside a tuple:
a = 1, 2, (3, 4, 5), 6
assert len(a) == 4
or when passing a literal tuple as argument to a function:
function(1, 2, 3, 4, 5, 6) # six arguments
function(1, 2, (3, 4, 5), 6) # four arguments
--
Steven
More information about the Tutor
mailing list