7.6 List vs. array
Performance: Introducing %timeit
Most array
operations execute significantly faster than corresponding list operations. To demonstrate, we’ll use the IPython %timeit
magic command, which times the average duration of operations. Note that the times displayed on your system may vary from what we show here.
Timing the Creation of a List Containing Results of 6,000,000 Die Rolls
We’ve demonstrated rolling a six-sided die 6,000,000 times. Here, let’s use the random
module’s randrange
function with a list comprehension to create a list of six million die rolls and time the operation using %timeit
. Note that we used the line-continuation character (\
) to split the statement in snippet [2]
over two lines:
In [1]: import random ...
Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.