What is faster? Two list comprehensions or one and a list.copy()?

Question:

Which of the following is faster?

a = ['' for _ in range(len(x))]
b = ['' for _ in range(len(x))]

or

a = ['' for _ in range(len(x))]
b = a.copy()

Thanks in advance!

Asked By: smyril

||

Answers:

You can see for yourself easily with a timing decorator:

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        print(f'func:{f.__name__} args:[{args}, {kw}] took: {te-ts} sec')
        return result
    return wrap

x = 10000000
@timing
def a(x):
    a = ['' for _ in range(x)]
    b = [i for i in a]
@timing
def b(x):
    a = ['' for _ in range(x)]
    b = a.copy()

a(x)
b(x)
Answered By: matszwecja