[Tutor] appending to a list
alan.gauld at btinternet.com
Thu Jan 31 09:39:32 CET 2008
"David Bear" <david.bear at asu.edu> wrote
>I want to return a tuple from a function. I want to append the second
> element of that tupple to a list. For example
> mylist = 
> def somefunc():
> return(3.14, 'some string')
> somenum, mylist.append(??) somefunc()
> obviously, the syntax doesn't work.
The problem here is that you are trying to combine
too many advanmced features in one step. You can
pass back a tuple into a tuple. Or you can pass
back an N-tuple and unpack it into N variables.
Or you can pass back an N-tuple and select
one of the elements. But you can't combine any
two of these in one step.
So if you only want to append the second element
and throw away the first, you can do it. Otherwise
you have to either store the results in a tuple and
access them seperatly later, or unpack into two
vars and append the second var.
t = somefunc()
somenum = t
somenum, someval = somefunc()
mylist.append(somefunc()) # losing the first value
> This should be easy,
Why should it be easy? :-)
The syntax for unpacking tuples hides what is a complex
operation in most languages which a) don't allow the
passing of tuples and b) dont support auto unpacking
of tuples. Its only the fact that Python allows this in one
move that makes it appear that is should be easy to access
the tuple elements anonymously.
FWIW To do this in C you would have to explicitly
create a struct or array inside the function and pass
back a pointer to the struct. Then in the calling code
you would have to explicitly dereference the struct elements
and then, finally, dispose of it. - Python makes it all
much easier, but still has its limits.
Author of the Learn to Program web site
More information about the Tutor