Tuple Comprehension ???

Cameron Simpson cs at cskk.id.au
Tue Feb 21 01:51:50 EST 2023


On 20Feb2023 19:36, Hen Hanna <henhanna at gmail.com> wrote:
>For a while,  i've been curious about a  [Tuple   Comprehension]
>
>So  finally   i tried it, and the result was a bit surprising...
>
>X= [ x for x in range(10) ]

This is a list comprehension, resulting in a list as its result.

>X= ( x for x in range(10) )

This is not a tuple comprehension - Python does not have one.

Instead, it is a generator expression:

     x for x in range(10)

inside some brackets, which are just group as you might find in an 
expression like:

     (3 + 4) * 7

If you want a tuple, you need to write:

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

which makes a tuple from an iterable (such as a list, but anything 
iterable will do). Here the iterable is the generator expression:

     x for x in range(10)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list