Lists vs Tuples

Python
Author

Imad Dabbura

Published

November 6, 2022

Tuples and Lists are referential data structures (container sequence), which means each element in them is just a pointer to objects but not the objects themselves. This is what allowed them to contain elements of different types. Compare that with arrays (flat sequence) that hold the actual elements, which requires all elements to be of the same type.

They share some of the same characteristics such as search time which is O(n). However, there are some differences that makes tuples preferred over lists in certain circumstances as is seen in the Python interpretter especially when the object’s size is not expected to change.

%timeit l = [0,1,2,3,4,5,6,7,8,9] #=> 60.5 ns ± 0.357 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
%timeit t = (0,1,2,3,4,5,6,7,8,9) #=> 11.9 ns ± 0.255 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)
dis.dis("(1, 2)")
  1           0 LOAD_CONST               0 ((1, 2))
              2 RETURN_VALUE

dis.dis("[1, 2]")
  1           0 LOAD_CONST               0 (1)
              2 LOAD_CONST               1 (2)
              4 BUILD_LIST               2
              6 RETURN_VALUE
t = (1, 2)
tuple(t) is t #=>  True

l = (1, 2)
list(l) is l #=>  False
sys.getsizeof(tuple(iter(range(10)))) #=> 120
sys.getsizeof(list(iter(range(10)))) #=> 136