简体   繁体   中英

Python 3.x list comprehension VS tuple generator

Is there any reason for memory, speed or whatever, that I would want to use:

tuple(i for i in range(5000))

instead of:

[i for i in range(5000)]

If I didn't mind the immutability of tuples

Basically a list comprehension is faster than a generator expression and as the reason is that its iteration performs in C (Read the @Veedrac's comment for the reason). But the only reason that should use a generator expression within tuple is that you want to perform some operations on your items and/or filter them and more importantly you want a tuple (because of the immutability and its benefits against mutable objects).

After all you can always timeit your code:

In [10]: %timeit tuple(i for i in range(5000))
1000 loops, best of 3: 325 µs per loop

In [11]: %timeit [i for i in range(5000)]
1000 loops, best of 3: 199 µs per loop

Also note that as I mentioned, if you want to use comprehensions you must needed to perform an operation on your items otherwise you can call the function directly on your iterator, which is faster:

In [12]: %timeit list(range(5000))
10000 loops, best of 3: 98.3 µs per loop

Generator expressions (or genexps , for short) are best used in loops to save memory when handling a lot of data. It's not considered good practice to expand a genexp to an interable data type (such as a list, tuple, set).

Also keep in mind that range() in Python 3 is like xrange() in Python 2. It returns a generator. In fact, xrange() tends to be faster even for 5000. Note: xrange() does not exist in Python 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM