Cost of operations on lists

Inserting elements at the end of a list


In [ ]:
%matplotlib inline
from matplotlib.pyplot import plot

from time import time

data = []
for i in range(1000, 50001, 1000):
    L = []
    before = time()
    for _ in range(i):
        L.append(None)
    after = time()
    data.append((i, after - before))
plot(*tuple(zip(*data)))
print()

Inserting elements at the beginning of a list


In [ ]:
%matplotlib inline
from matplotlib.pyplot import plot

from time import time

data = []
for i in range(1000, 50001, 1000):
    L = []
    before = time()
    for _ in range(i):
        L.insert(0, None)
    after = time()
    data.append((i, after - before))
plot(*tuple(zip(*data)))
print()

Size of a list initialised to a given number of elements


In [ ]:
%matplotlib inline
from matplotlib.pyplot import plot

from sys import getsizeof

data = []
for i in range(1, 51):
    data.append((i, getsizeof([None] * i)))
plot(*tuple(zip(*data)))
print()

Size of a list to which elements are appended incrementally


In [ ]:
%matplotlib inline
from matplotlib.pyplot import plot

from sys import getsizeof

data = []
L = []
for i in range(1, 51):
    L.append(None)
    data.append((i, getsizeof(L)))
plot(*tuple(zip(*data)))
print()