Salma Salma - 2 months ago 4x
Python Question

Assigning values to multiple names

I have seen many Python snippets where they write something like this:

labels, features = targetFeatureSplit(data)

or something like

ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths, test_size=0.1, random_state=42)

How are they assigning these values?


So if you have a function that returns two values like so:

def example():
    return 'alice', 'bob'

You can then call this function and set it to the variable test.

test = example()

where test is a tuple of 'alice' and 'bob'.

You can instead assign what the function returns to two variables instead, for example,

a, b = example()

where a is 'alice' and b is 'bob'.

To answer the last bit of your question - if a function does not have a return keyword in it, then it will return None when the function completes. Therefore for variable assigment you can only set one variable equal to what this function returns.