Lists vs tuples (newbie)

Alexander Schmolck a.schmolck at gmail.com
Mon May 21 08:44:27 EDT 2007


Szabolcs <szhorvat at gmail.com> writes:

> Thanks for all the replies!
>
> Phoe6 wrote:
>> 1) Return values from a function.  When you return multiple values
>> from a function. You store them as a tuple and access them
>> individually rather then in the list, which bear the danger of being
>> modified.
>> Look up the standard library itself and you will find many instances.
>>
>> (cin, cout, cerr) = os.popen3('man man')
>>
>> If you had the above as list, then you might end up spoiling things
>> knowingly/unknowingly.
>
> Could you please elaborate on this (or give an explicit example how might one
> do something bad unknowingly when returning multiple values in a list)?


    def f(input, defaultAnswer=[1,2,3]):
        if input == 1: return (4,5,6)
        else: return defaultAnswer

    print f(0).pop(), f(0).pop(), f(0).pop(), f(0)
    

But that's a pretty pathological; just using unstructuring as in the open
example above nothing bad can happen.

>
> Should I think of tuples simply as a safeguard and reminder (because I
> consciously use them for different thing than lists, as the faq suggests)?

Use them for hetoerogeneous data or when you need the immutability (so that
people can't screw)

'as



More information about the Python-list mailing list