Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to return two lists from a list comprehension?

Is it possible to return two lists from a list comprehension? Well, this obviously doesn't work, but something like:

rr, tt = [i*10, i*12 for i in xrange(4)] 

So rr and tt both are lists with the results from i*10 and i*12 respectively. Many thanks

like image 381
LarsVegas Avatar asked May 07 '12 08:05

LarsVegas


People also ask

Does list comprehension return a list?

List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

Can list comprehension be nested?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.

Can you return a list comprehension Python?

return is a statement. List comprehensions cannot contain statements, only expressions. In fact, that's true for all expressions in Python: they can only contain other expressions. So, no, you can't put a return inside a list comprehension.


Video Answer


1 Answers

>>> rr,tt = zip(*[(i*10, i*12) for i in xrange(4)]) >>> rr (0, 10, 20, 30) >>> tt (0, 12, 24, 36) 
like image 151
jamylak Avatar answered Sep 21 '22 09:09

jamylak