Home > Software engineering >  Calling a function using a list in my argument. Why is the return type a tuple?
Calling a function using a list in my argument. Why is the return type a tuple?

Time:01-21

def get_age_and_name(user_data):
  age = user_data[2]
  name = user_data[0]
  return age, name

user = ["Ann", "Davis", 35]
print(get_age_and_name(user))

#Q1) user is a list but my return is a tuple. Why? i think it should be a list because of parameter. #Q2) I am trying to find the class of local variable 'age' but getting a non-defined error in VS Code

print (type(age)) 

Q#1) I was expecting return class type to be a list Q#2) I was exepcting age type to be a list but I get an error

CodePudding user response:

The statement:

return age, name

is equivalent to:

return (age, name)

It constructs a two-element tuple whose first element is age and whose second element is name, and returns it. That's the normal way for a function to return multiple values in Python.

If you want to unpack the values in the caller, you can call it as:

age, name = get_age_and_name(user)

This will set age to the first element of the tuple and name to the second element of the tuple. You can, of course, also just use the return value as a tuple.

CodePudding user response:

Q1) If more than one value is returned from a function, Python will naturally return them as a tuple. The input value does not define a function's output. You can define a list as the data type you want by simply wrapping your values in square brackets like this:

  def get_age_and_name(user_data):  
  age = user_data[2] 
  name = user_data[0]  
  return [age, name]

Q2) In your example, age is a local variable, meaning it's defined in a function. That variable cannot be called outside of that function. That is why you're receiving the not-defined error. You can try printing the type of the variable within the function or if you want it outside the function try something like: print(type(user[2])) or print(type(get_age_and_name(user)[0]))

Both would have similar results. Hope this helps.

  • Related