-2

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!

smyril
  • 111
  • 10
  • Hard to say considering both codes will not run due to syntax problems. – matszwecja Oct 19 '22 at 11:29
  • An important thing as well is that those 2 snippets do 2 **very** different things, which makes comparing them pointless. – matszwecja Oct 19 '22 at 11:31
  • They do very different things, the first one creates a lot of empty lists twice, the second one does only creates them once and then copy a reference to them, if the first one has 2 N empty lists, the second one only has N empty lists, referenced from both a and b. – luk2302 Oct 19 '22 at 11:32
  • the .copy() is preventing the reference problem – smyril Oct 19 '22 at 11:36
  • It's not. You are copying references to the same inner lists. – matszwecja Oct 19 '22 at 11:37
  • 1
    You can very easily see that by adding anything to one of the empty lists and looking at the other one - added element will be visible inside the other list as well. – matszwecja Oct 19 '22 at 11:38
  • ahh ok didnt think about that, what if i did the same thing but with strings inside my lists? – smyril Oct 19 '22 at 11:39
  • Edit the question to show what exactly you have in mind. – matszwecja Oct 19 '22 at 11:40

1 Answers1

1

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)
matszwecja
  • 6,357
  • 2
  • 10
  • 17
  • Thats pretty cool! could you explain how this works? – smyril Oct 19 '22 at 13:49
  • Sure, it's just a decorator that wraps the decorated function, storing a time before and after function call. It's taken from [this answer](https://stackoverflow.com/a/27737385/9296093), updated to Python 3. The decorators are sort of wrapper functions that can do some stuff to the function they are decorating. – matszwecja Oct 19 '22 at 13:53
  • does that mean that I can use the timing decorator and function to measure the time of a function while it still working normal? – smyril Oct 20 '22 at 08:49
  • Yes, any function decorated with this will do its job as normal, but it will also print the message each time it finishes. – matszwecja Oct 20 '22 at 08:50
  • maybe you could take a look at this: https://stackoverflow.com/q/74151564/15018486 – smyril Oct 21 '22 at 09:27