Tuple Comprehension ???

avi.e.gross at gmail.com avi.e.gross at gmail.com
Tue Feb 21 01:23:31 EST 2023


Tuples are immutable and sort of have to be created all at once. This does
not jive well wth being made incrementally in a comprehension. And, as
noted, the use of parentheses I too many contexts means that what looks like
a comprehension in parentheses is used instead as a generator.

If you really want a tuple made using a comprehension, you have some options
that are indirect.

One is to create a list using the comprehension and copy/convert that into a
tuple as in:

mytuple = tuple( [x for x in range(10) ] )

I think an alternative is to use a generator in a similar way that keeps
being iterated till done.

mytuple = tuple( (x for x in range(10) ) )

And similarly, you can use a set comprehension and convert that to a tuple
but only if nothing is repeated and perhaps order does not matter, albeit in
recent python versions, I think it remains ordered by insertion order!

mytuple = tuple( {x for x in range(10) } )

There are other more obscure and weird ways, of course but generally no
need.

Realistically, in many contexts, you do not have to store or use things in
tuples, albeit some sticklers think it is a good idea to use a tuple when
you want to make clear the data is to be immutable. There can be other
benefits such as storage space used. And in many ways, tuples are supposed
to be faster than lists.

-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On
Behalf Of Michael Torrie
Sent: Monday, February 20, 2023 10:57 PM
To: python-list at python.org
Subject: Re: Tuple Comprehension ???

On 2/20/23 20:36, Hen Hanna wrote:
> For a while,  i've been curious about a  [Tuple   Comprehension] 

I've never heard of a "Tuple comprehension."  No such thing exists as far as
I know.

> So  finally   i tried it, and the result was a bit surprising...
> 
> 
> X= [ x for x in range(10) ]
> X= ( x for x in range(10) )
> print(X)
> a= list(X)
> print(a)

What was surprising? Don't keep us in suspense!

Using square brackets is a list comprehension. Using parenthesis creates a
generator expression. It is not a tuple. A generator expression can be
perhaps thought of as a lazy list.  Instead of computing each member ahead
of time, it returns a generator object which, when iterated over, produces
the members one at a time.  This can be a tremendous optimization in terms
of resource usage.  See
https://docs.python.org/3/reference/expressions.html#generator-expressions.
 Also you can search google for "generator expression" for other examples.

--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list