Which one is faster to access list or a tuple and why?
Tuple is slightly faster to access than list.
Tuples are immutable data types which are stored in a single block of memory so it doesn’t require extra space to store new objects.
But list are mutable data types and are allocated in two blocks where the fixed one with all object information and a variable sized block for the data.
There is slight difference in indexing speed of list and tuple because tuples uses fewer pointers when indexing than that of list. Becuase of fewer pointers, acess mechanism is generally faster in tuples than lists.
Following program compares speed benchmark for list and tuple.
List & Tuple Speed Comparison
# Tuple and List Performance Benchmark
# Importing required modules
import random
import time
# Creating list of 2,000,000 containing
# random numbers between 1 and 5,000,000
my_list = random. sample(range(1, 5000000), 2000000)
# converting list to tuples
my_tuple = tuple(my_list)
# BENCHMARKING FOR LIST
# Measuring start time
start_list = time.time()
# Accessing random elements from list 500,000 times
for i in range(500000):
element = my_list[random.randint(0, 500000)]
# Measuring stop time
stop_list = time.time();
list_time = stop_list - start_list
# BENCHMARKING FOR TUPLE
# Measuring start time
start_tuple = time.time()
# Accessing random elements from tuple 500,000 times
for i in range(500000):
element = my_tuple[random.randint(0, 500000)]
# Measuring stop time
stop_tuple = time.time();
tuple_time = stop_tuple - start_tuple
# Displaying results
print('Tuple = %0.6f seconds' % (tuple_time))
print('List = %0.6f seconds' % (list_time))
Output
Run 1: ------------ Tuple = 2.307861 seconds List = 2.362857 seconds Run 2: ------------ Tuple = 2.339859 seconds List = 2.340859 seconds Run 3: ------------ Tuple = 2.335859 seconds List = 2.330854 seconds Run 4: ------------ Tuple = 2.395857 seconds List = 2.655840 seconds Run 5: ------------ Tuple = 2.291866 seconds List = 2.309857 seconds
Result of above program shows that, access time for tuple is faster for 4 tests out of 5 tests performed than list.
So, we can say that tuple is slighlty faster than list. This program is executed on Intel core I3, 6GB RAM & Python 3.8.2. On your machine you will get slightly different results.