Understanding python for multiple return function

I have a function that returns two values, and I would like to use list comprehension to populate two lists. eg:

def f(x):
  return 2*x,x*x

x = range(3)
xlist, ylist = [f(value) for value in x]

EDITS from answers below:
xtuple, ytuple = zip(*[f(value) for value in x])
xlist, ylist = map(list,zip(*[f(value) for value in x]))

where the expected return should be:

xlist = [0, 2, 4]
ylist = [0, 1, 4]

my question comes down to:

I am currently getting a list of tuples, while this is reasonable, I will need two independent lists. currently I can have a variable 1 placeholder (tuple) and 3 full understandings. But I am wondering if there is a clean way to do this using a single list.

It is worth noting: in real code, my two returns are correlated, so I can’t just split the function into two.

+4
source share
4

, : :

[f(value) for value in x]
#  ^ notice the `value`

:

[f(x) for value in x]

, , :

return 2*x,x

:

return (2*x,x)

. , , . zip , :

xlist,ylist = zip(*[f(value) for value in x])
#                 ^ with asterisk

, xlist ylist ( zip ). , , , , :

xlist,ylist = map(list,zip(*[f(value) for value in x]))

:

>>> xlist
[0, 2, 4]
>>> ylist
[0, 1, 4]

(, range 0)

. , :

xlist = [f(value)[0] for value in x]
ylist = [f(value)[1] for value in x]

, , , , (, f ).

+6

zip(),

def f(x):
  return 2*x, x*x

x = range(1, 4)
xlist, ylist = zip(*[f(value) for value in x])

print(xlist, ylist)
# ((2, 4, 6), (1, 4, 9))
+5

. :

def f(x):
  return 2*x, x*x

: :

x = range(1, 4)

, , list. , zip(*lst) :

xlist, ylist = zip(*[f(value) for value in x])

, :

xlist 
=> [2, 4, 6]
ylist 
=> [1, 4, 9]
+5

zip(*your_list_of_bituples)

demo_list = [(1, 2), (2, 3), (4, 5)]
zip(*demo_list)

[(1, 2, 4), (2, 3, 5)]
+3

Source: https://habr.com/ru/post/1670460/


All Articles