Can Python function return multiple data?

Chris Angelico rosuav at gmail.com
Fri Jun 5 17:59:22 EDT 2015


On Fri, Jun 5, 2015 at 11:29 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> On Friday, June 5, 2015 at 4:36:35 PM UTC+5:30, Steven D'Aprano wrote:
>> On Fri, 5 Jun 2015 01:16 pm, Rustom Mody wrote:
>> > The abstract platonic immutable list is non-existent in python
>>
>> Just pretend that "immutable list" is spelled "tuple".
>
> Ok lets say I make no fuss about the need to 'pretend'.
>
> And I try...
>
>>>> a=[1,2,3]
>>>> b=(a,a)
>>>> a
> [1, 2, 3]
>>>> b
> ([1, 2, 3], [1, 2, 3])
>>>> a.append(4)
>>>> b
> ([1, 2, 3, 4], [1, 2, 3, 4])

Congrats! You just proved that an object can itself be immutable, but
can contain references to mutables. Ain't that awesome?

Did you have a point?

> It was an analogy.
> C programmers use lists all right all the time.
> However until they see something like python, they dont know that they never
> REALLY saw lists. ie lists in python are more first-class than C.

If you're talking about the things C programmers use all the time,
they're not linked lists, they're arrays - identified by base pointer
and element count. Linked lists are common in LISPy languages, but not
all that common in C, nor C-derived APIs. Most APIs designed for C
usage are either array-based or generator-based.

http://www.gnu.org/software/libc/manual/html_node/Scanning-Directory-Content.html
Array-based: scandir accepts a pointer-to-pointer, which it populates
with a pointer to freshly-allocated data, and it returns the number of
entries stashed there.

http://www.gnu.org/software/libc/manual/html_node/Opening-a-Directory.html
http://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html
Generator-based: opendir returns a generator, readdir gives the next
result or NULL

http://www.gnu.org/software/libc/manual/html_node/Array-Sort-Function.html
Array-based: pass it a base pointer and a count (and an object size,
since it's completely generic), and it sorts the elements.

Your point is still broadly valid, though; these arrays are not
first-class objects. They do have their own little quirks; so long as
the original array isn't deallocated, you can efficiently work with
views by simply using a base pointer inside the original array and a
length that's shorter than the whole array. Very convenient if you
need it, but most certainly not first-class lists, and can cause
problems if you're not careful. Python lists truly are first-class
objects; "more first-class than C" in the sense that 1 is more true
than 0.

ChrisA



More information about the Python-list mailing list