Python Find Element in List or Dictionary, Which is Faster? – Python Performance Optimization

By | November 18, 2020

We often use python list and dictionary to store some elements, we can use if in statement to check an element in a list or dictionary or not. However, Should we use python list or dictionary? Which one is faster? In this tutorial, we will give you an answer.

Please look at this example code below:

import time
data_list = list(range(1000000))
data_dict = {}
for i in range(1000000):
    data_dict[i] = i

We have saved 1,000,000 elements in a python list and dictionary.

Then we will find a element from them and calculate the time spent.

In order to learn how to calculate the time spent by python script, there are some ways, you can refer:

Calculate the Execution Time of a Python Program – A Step Guide – Python Tutorial

Calculate the time spent by python list and dictionary

We will find 98,090 in python list and dictionary.

starttime = time.clock()
if 98090 in data_list:
    print('data in list')
    endtime = time.clock()
    t1 = endtime - starttime
    print("time spent about "+str(t1)+" senconds")

starttime = time.clock()  
  
if 98090 in data_dict:
    print('data in dict')
    endtime = time.clock()
    t2 = endtime - starttime
    print("time spent about "+str(t2)+" senconds")
    print(t1/t2)

Run this code, we can find:

Python Find Element in List or Dictionary, Which is Faster? - Python Performance Optimization

if in takes 0.010229499999999999 senconds in python list, takes 4.3399999999998995e-05 senconds in python dictionary. The times is 235.70276497696395.

It means that if we should find an element, we should use python dictionary, it is faster than list.

Leave a Reply

Your email address will not be published. Required fields are marked *