How to create a tuple quickly with list comprehension?

Hatem Nassrat hnassrat at gmail.com
Fri Oct 10 15:10:29 EDT 2008


on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote:
>markacy wrote:
>
>> On 13 Cze, 09:45, "fdu.xia... at gmail.com" <fdu.xia... at
>> gmail.com> wrote:
>>> Hi all,
>>>
>>> I can use list comprehension to create list quickly. So I
>>> expected that I
>>> can created tuple quickly with the same syntax. 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))
>>>
>>> In [148]: b = [i for i in range(10)]
>>>
>>> In [149]: type(a)
>>> Out[149]: <type 'generator'>
>>>
>>> In [150]: type(b)
>>> Out[150]: <type 'list'>
[...]
 
>> You should do it like this:
>> 
>>>>> a = tuple([i for i in range(10)])
>>>>> type(a)
>> <type 'tuple'>
[...]

>No need to create the intermediate list, a generator
>expression works just
>fine:
>
>a = tuple(i for i in range(10))


Well I have looked into this and it seems that using the list
comprehension is faster, which is reasonable since generators require
iteration and stop iteration and what not.

    # If you really really want a tuple, use [24] style
    # if you need a generator use [27] style (without the tuple keyword
    # off course)

    In [24]: %timeit tuple([x for x in range(1000)])
    10000 loops, best of 3: 185 µs per loop

    In [25]: %timeit tuple([x for x in range(1000)])
    1000 loops, best of 3: 195 µs per loop

    In [26]: %timeit tuple([x for x in range(1000)])
    10000 loops, best of 3: 194 µs per loop

    #################################################

    In [27]: %timeit tuple((x for x in range(1000)))
    1000 loops, best of 3: 271 µs per loop

    In [28]: %timeit tuple((x for x in range(1000)))
    1000 loops, best of 3: 253 µs per loop

    In [29]: %timeit tuple((x for x in range(1000)))
    1000 loops, best of 3: 276 µs per loop

Thanks

-- 
Hatem Nassrat



More information about the Python-list mailing list