I've been having a lot of trouble finding documentation on this. What is the time complexity of list.count() in Python 3? I've been assuming it's just O(n), does anyone know if this is the case?
You can try a bit of an experiment using the timeit
module.
Timing list.count(0)
over a large range of list lengths ( 10**0
to 10**6
).
from timeit import timeit
from math import log10
import matplotlib.pyplot as plt
data = []
for i in [10**x for x in range(6)]:
data.append((i, timeit.timeit('x.count(0)', setup='x=list(range(%d))' % i, number=1000)))
Taking the log of both time and list length for better visualisation (note we are using log10
here, to match the range of list lengths).
log_data = [log10(x), log10(y) for (x,y) in data]
Generate a quick plot.
plt.figure()
plt.scatter(*zip(*log_times))
plt.xlabel('log(n)')
plt.ylabel('log(time)')
plt.savefig('count_complexity')
It seems that it is indeed O(n) complexity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.