How to create a tuple quickly with list comprehension?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jun 13 05:59:31 EDT 2007


"fdu.xiaojf at gmail.com" <fdu.xiaojf at gmail.com> writes:

> I can use list comprehension to create list quickly. So I expected
> that I can created tuple quickly with the same syntax.

Nope. The list comprehension syntax creates lists.

> But I found that the same syntax will get a generator, not a
> tuple. Here is my example:
>
> In [147]: a = (i for i in range(10))

This contains no commas, so I don't know why you think it has anything
to do with a tuple.

Bear in mind that parentheses have nothing to do with the syntax for
creating a tuple; the parentheses merely determine parsing order, and
can enclose any expression.

> Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9)
> quickly?

    tuple(range(1, 10))

-- 
 \    "Know what I hate most? Rhetorical questions."  -- Henry N. Camp |
  `\                                                                   |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list