Skip to content
Advertisement

How can I get multiple lists as separate results from a list comprehension?

Suppose I have this code:

JavaScript

How can I neatly get a result like this?

JavaScript

Advertisement

Answer

Note that return 2*x,x is short for return (2*x,x), i.e. a tuple. Your list comprehension thus generates a list of tuples, not a tuple of lists. The nice thing of zip however is that you can easily use it in reverse with the asterisk:

JavaScript

Note that xlist and ylist will be tuples (since zip will be unpacked). If you want them to be lists, you can for instance use:

JavaScript

which results in:

JavaScript

Another way to do this is with separate list comprehensions:

JavaScript

Of course, this repeats the work of f, which is inelegant and can be inefficient.

Advertisement