Tuples vs Lists in Python 3

November 1, 2015

Creating tuples from generator expression is surprisingly fast.


from timeit import timeit

setup = 'a = (i for i in range(100))'
print("Setup: {}".format(setup))

tuple_code = 'tuple(a)'
list_code = 'list(a)'
print("Tuple code: {}".format(tuple_code))
print("List code: {}".format(list_code))

tuple_time = timeit('tuple(a)', setup)
list_time = timeit('list(a)', setup)
print("Tuple creation: {} seconds".format(tuple_time))
print("List creation: {} seconds".format(list_time))

    "Tuple creation was {:.2f} times faster".format(
        float(list_time) / tuple_time, 2


Setup: a = (i for i in range(100))
Tuple code: tuple(a)
List code: list(a)
Tuple creation: 0.33144659000390675 seconds
List creation: 0.6380892739980482 seconds
Tuple creation was 1.93 times faster

Speed up by a factor of 2!

I would be thrilled to hear from you! Please share your thoughts and ideas with me via email.

Back to Index