[Tutor] Returning multiple objects from a function
Walter Prins
wprins at gmail.com
Tue Jul 3 10:38:18 CEST 2012
Hi
On 3 July 2012 03:23, Alexander Q. <redacted@example.com> wrote:
> > Traceback (most recent call last):
> File "C:\Users\Owner\Desktop\MIT\Sets\Set3.py", line 34, in <module>
> list4 = tuplesresult[1]
> TypeError: 'NoneType' object is not subscriptable
Ok as a bit of clarification: When you have a function that doesn't
actually return anything, for example:
def mainFunc()
print "I don't return anything..."
And you then do:
x = mainFunc()
... then x will contain the value None with the type NoneType.
If you then try to index into x, e.g...
print x[0]
... you will get the error above, which is saying the the type of the
variable x, (e.g. NoneType) is not subscriptable, that is, you cannot
index into it.
So, what you have to ask yourself is where/how you omitted to have
mainfunc return some values. (As per Dave's answer, if you have for
example conditional return statements it's probably possibe for
mainFun() to run without returning anything.)
> When I tried to assign "tuplesresult[1]" to the variable "list4" (after
> assigning tuplesresult = mainFunc(), which is the name of the function that
> returns the tuple in my program), the error occurred. That aside, is it all
> right if I just code "return list1, list2" without the parens? In that case,
> how would I access list1 and list2 when needed?
Yes, Python will automatically package the result into a tuple just the same.
Please note, I forgot to mention in my original reply the automatic
tuple unpacking mechanism in Python as mentioned by Alan. In your
case (as in many cases), it's probably the more Pythonic/neater way to
express yourself. If your function is returning 4 lists say, then
rather than getting all 4 in a tuple first and then unpacking them
manually yourself, you can just do...
list1, list2, list3, list4 = mainFunc()
HTH,
Walter
More information about the Tutor
mailing list