简体   繁体   中英

Limit on the number of values returned by a Python function/method

I was working with some code and realised that things became a lot easier when a single method was returning 4 values. Working with traditional languages like C++ and Java where methods return only a single value, I came to wonder

Is there a limit on the number of values returned by a Python function?

Stuff like this works effortlessly. Is there a limit to it?

def hello():
    return 1, 2, 3, 4, 5

a, b, c, d, e = hello()
print a, b, c, d, e


Stragely enough, I didn't find any answer to this question

If you return multiple values, you actually return a tuple . Indeed:

return 1,4,2,5

is short for:

return (1,4,2,5)

So the question boils down to how many items a tuple can carry . The answer can be obtained with:

import sys

It is usually 2 31 -1=2 147 483 647 on a 32-bit system and 2 63 -1=9 223 372 036 854 775 807 on a 64-bit system. The strange thing is: it is not 2 32 -1 (or 2 64 -1) so that means that technically speaking if you have a 32-bit machine, and your have 4 GiB in place, the list itself can only fill up half of the memory (of course the elements in the list can be responsible to fill up the remaining half).

Of course the elements also need to fit into memory: if you have no space left to store five million elements, your program will crash anyway.

Python functions only return a single value: a reference to an object. That object may be of any type, including a tuple (which is what's constructed with return 1, 2, 3, 4, 5 ). The size of the object is only limited by your computer's available memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM