user189035
user189035

Reputation: 5789

Python list unpacking, is this expensive? Is it inefficient?

Suppose I have a Python function that returns multiple elements, for example myfoo0()

def myfoo0():
   return([1, 2, 3])

and that this is used as:

fit = myfoo0();

Now, consider a function that used some of the entries of fit as input. For example:

def myfoo1(fit):
   [a, b, c] = fit
   return(doSomething(a))

Now, I find it easier to read the intend if I write this as:

fit = myfoo0();
out = myfoo1(fit)

(an example is when I have many functions myfoo1,...,myfoon each using different components of fit) my question is how does the above code (with a naming of the entries of fit inside the body of myfoo1) compares (from a performance point of view) to this one:

[a, b, c] = myfoo0();
out = myfoo2(a)

where

def myfoo2(a):
   return(doSomething(a))

In particular, is the solution with tuple unpacking inside the function incur a significant additional cost (for example in terms of copying)?

Upvotes: 0

Views: 496

Answers (1)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 2914

There are some misconceptions here:

  1. fit = myfoo0(); doesn't copy anything. fit is merely a reference to the list returned by myfoo0(), not a copy.

  2. [a, b, c] = myfoo0(); doesn't create a new list as well. On the otherhand, you have 3 variables being references to the first, second and third list members respectively.

  3. out = myfoo1(fit) is not the same myfoo1(a). The first call invokes myfoo1 with a list passed as first argument, the second call invokes myfoo1 with the first list member passed as first argument.

Upvotes: 2

Related Questions