Is it faster to add a key to a dictionary or append a value to a list in Python?
<p>I have an application where I need to build a list or a dictionary and speed is important. Normally I would just declare a list of zeros of the appropriate length and assign values one at a time but I need to be able to check the length and have it still be meaningful.</p>

<p>Would it be faster to add a key value pair to a dictionary or to append a value to a list? The length of the lists and dictionary will usually be small (less than 100) but this isn't always true and in worst case could be much larger.</p>

<p>I could also just have a variable to keep track of where I am in the list if both of these operations are too slow.</p>

<p>Best way is to use <code>time()</code> to check your execution time.</p>

<p>In following example dict is slightly faster.</p>

<pre><code>from time import time

st_time = time()
b = dict()
for i in range(1, 10000000):
    b[i] = i

print (time() - st_time)

st_time = time()
a = []
for i in range(1, 10000000):
    a.append(i)

print (time() - st_time)

1.45600008965
1.52499985695
</code></pre>

python performance cpu-speed