Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old October 10th, 2008, 08:15 PM
Hatem Nassrat
Guest
 
Posts: n/a
Default Re: How to create a tuple quickly with list comprehension?

on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote:
Quote:
>markacy wrote:
>
Quote:
>On 13 Cze, 09:45, "fdu.xia... at gmail.com" <fdu.xia... at
>gmail.comwrote:
Quote:
>>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'>
[...]
Quote:
Quote:
>You should do it like this:
>>
Quote:
>>>>a = tuple([i for i in range(10)])
>>>>type(a)
><type 'tuple'>
[...]
Quote:
>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
 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles