Remove comma from tuples in python.

Tim Chase python.list at tim.thechases.com
Fri Feb 21 15:00:32 CET 2014


On 2014-02-21 09:29, Alister wrote:
> >    >>> seriesxlist1 = ((0.0,), (0.01,), (0.02,))
> >    >>> x2 = [x*x for (x,) in seriesxlist1]  
> > 
> > I tend to omit those parentheses and use just the comma:
> >   
> >    >>> x2 = [x*x for x, in seriesxlist1]  
> 
> I had not though of using unpacking in this way & would have written
> 
> x2= [x[0]**2 for x in serisexlist1]
> 
> I am not sure which is easier to read in this instance (single
> element tupple) but unpacking would definitely be the way to go if
> the tupple had multiple values.

With the single-value tuple, I tend to find the parens make it more
readable, so I'd go with

  [x*x for (x,) in lst]

whereas if they were multi-value tuples, I tend to omit the parens:

  [x*y for x,y in lst]

though, tangentially, Python throws a SyntaxError if you try and pass
a generator to a function without extra outer parens because it
makes parsing them ambiguous otherwise:

  >>>  x = sum(a+b for a, b in lst, 10)
  File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole
argument
  >>> x = sum((a+b) for a,b in lst), 10)
  [no error]

-tkc





More information about the Python-list mailing list