Literals vs Copy

Posted by Afsal on 25-Nov-2022

Hi Pythonistas!

Today we will compare the performance of literal vs copy (Shallow Copy). Let us check the same for the list and dict. Let us dive into the code

Code

import timeit
import copy

a = list(range(100))
q = { i: i for i in range(100) }

def using_list_literal():
    b = list(a)
    return b

def list_copy():
    b = copy.copy(a)
    return b

def using_dict_literal():
    b = dict(q)
    return b

def dict_copy():
    b = copy.copy(q)
    return b

time_for_list_literal = timeit.timeit(using_list_literal, number=1000_000)
print("Time for list literal: ", time_for_list_literal)

time_for_list_copy = timeit.timeit(list_copy, number=1000_000)
print("Time for list copy: ", time_for_list_copy)

time_for_dict_literal = timeit.timeit(using_dict_literal, number=1000_000)
print("Time for dict literal: ", time_for_dict_literal)

time_for_dict_copy = timeit.timeit(dict_copy, number=1000_000)
print("Time for dict copy: ", time_for_dict_copy)

Output

Time for list literal:  0.21742131199999903
Time for list copy:  0.2580612790000032
Time for dict literal:  0.37704453300000296
Time for dict copy:  0.4378888429999961

We can see that the literals are faster for both cases than the copy. Also, code using literal is more pythonic.

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in