Mailing List Archive

Tuple Comprehension ???
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) ]
X= ( x for x in range(10) )
print(X)
a= list(X)
print(a)



--
https://mail.python.org/mailman/listinfo/python-list
Re: Tuple Comprehension ??? [ In reply to ]
On 20Feb2023 19:36, Hen Hanna <henhanna@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@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list