Search code examples
pythonpython-3.xlistperformancegenerator

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


Solution

  • 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