liv2hak
liv2hak

Reputation: 14970

returning multiple values in python

I am trying to analyze and understand a python program the implements a simple map-reduce idea. I have some difficulty in understanding some code.

Person = namedtuple('Person', ['name', 'gender', 'age', 'height'])

persons = [
    Person('mary', 'fem', 21, 60.2),
    Person('suzy', 'fem', 32, 70.1),
    Person('jane', 'fem', 27, 58.1),
    Person('jill', 'fem', 24, 69.1),
    Person('bess', 'fem', 43, 66.6),
    Person('john', 'mal', 25, 70.8),
    Person('jack', 'mal', 40, 59.1),
    Person('mike', 'mal', 42, 60.3),
    Person('zack', 'mal', 45, 63.7),
    Person('alma', 'fem', 34, 67.0),
    Person('bill', 'mal', 20, 62.1),
]

def height_by_gender_and_agegroup(p):
    key = p.gender, p.age //10
    val = p.height
    return key, val

The function height_by_gender_and_agegroup(p) seems to return two values for each p. It seems to return

<key,val> where key is p.gender and val is p.height
<key,val> where key is p.age and val is p.height

I have been programming in C and C++ but am quite new to python. My question is how does returning multiples pairs by value work in Python. i.e assuming that that is what this code is doing. If yes how do I process the return values?

the answers below seem to convey the fact that returning a key-value pair in python is similar to returning a struct with two members.I understand that part.

 key = p.gender, p.age //10

My question is on the above line.Key seems to take two values p.gender and p.age.If that is the case there need to be two sets of <key,value> returned for every value of P. How does this work?

Upvotes: 0

Views: 384

Answers (3)

David Robinson
David Robinson

Reputation: 78590

What it is returning is a tuple of two items. (It is basically equivalent to returning a struct with two fields in C). You can unpack the returned tuple like this:

key, val = height_by_gender_and_agegroup(person)

It might help to think of it in this way:

def height_by_gender_and_agegroup(p):
    key = p.gender, p.age //10
    val = p.height
    return (key, val)  # note the optional parentheses to denote a tuple

ret = height_by_gender_and_agegroup(person)
key = ret[0]
val = ret[1]  # "key, val =" is just a shortcut for this

Since the key in your case contains two values, you can unpack it further:

(gender, age), val = height_by_gender_and_agegroup(person)

Or if you prefer:

key, val = height_by_gender_and_agegroup(person)
gender, age = key

Upvotes: 2

Hoopdady
Hoopdady

Reputation: 2356

You can say:

 k,v = height_by_gender_and_agegroup(p)

Upvotes: 2

kojiro
kojiro

Reputation: 77059

The function is actually returning a tuple.

>>> def f(): return 1, 2
... 
>>> type(f())
<type 'tuple'>

Like any tuple, you can access its values by subscript or by assigning the members in order:

>>> first, second = f()
>>> second
2

Upvotes: 2

Related Questions