Python: List and Tuple performance benchmark

Suppose you have two options to implement a solution using a programming language, what are important factors to select one of options? I do believe one of concerns for a programmer would be performance benchmark between those options.

In this short blog post I’d like to share my simple code and results for performance benchmark between Python list and tuple. Two features to create a list, but with this difference, that tuples are immutable and you can’t alter them after initializing.

Following code shows a simple usage of list and tuple to create a series of items:

# this is a list, you can alter it in next lines l = [1, 2, 3, 4, 5] # this is a tuple and it's immutable t = (1, 2, 3, 4, 5) 

Please note that you can store different data types as an item for both tuple and list.

My scenario to make a performance benchmark between list and tuple is retrieving 2,000,000 random items from a list (or tuple) with 1,000,000 items.

Here is the source code for list:

import time from random import randint x = 1000000 demo_list = [] # add items to list while x > 0: demo_list.append(x) x = x - 1 start = time.clock() # find random items from list y = 2000000 while y > 0: item = demo_list[randint(0, 999999)] y = y - 1 # print the elapsed time print (time.clock() - start) 

Following chart illustrates the performance benchmark between list and tuple on a Mac OS X 10.9.3 and Python 2.7.5:

Benchmark between list and tuple

Elapsed times:

And it seems tuples are a little bit faster in retrieving items.

You can download the source code for both list and tuple from my Github account:
https://github.com/afshinm/python-list-vs-tuple-benchmark

 
100
Kudos
 
100
Kudos

Now read this

Using CSS Fallback Properties for Better Cross-browser Compatibility

As you may know, Internet Explorer has supported something called conditional comments which allow you to include specific HTML or CSS based upon the result of a condition. Conditional comments in HTML first appeared in Microsoft’s... Continue →