3

Hi people of Stackoverflow,

I have a function which calculates a list and I want to return each element of the list individually, like so (the function receiving this return is designed to handle an undefined number of parameters):

def foo():
    my_list = [1,2,3,4]
    return 1,2,3,4

The number of elements in the list is undefined so I can't do:

return my_list[0], my_list[1], ...

I think there must be an easy solution to this but I can't seem to wrap my head around it. Any suggestions? Thanks!

EDIT: Thanks for your answers, so here is the extension to my problem, which is really my problem:

def foo():
    my_list = [1,2,3,4]
    return "any_other_value", my_list

So, what I want is that when I call foo(), bar = foo(), bar[0] = "any_other_value", bar[1] = 1, bar[2]=3, bar[3] = 4. And my_list is of undetermined length (here it has only 4 elements).

user11291
  • 53
  • 1
  • 1
  • 6
  • What are you trying to do? Functions will always return a single value, `1,2,3,4` is just a tuple and you might as well `return my_list` directly. – Jochen Ritzel Apr 12 '14 at 11:56
  • How will you catch these outputed individual elements. Would yield serve your purpose? – Abhishek Bansal Apr 12 '14 at 11:57
  • Hi! I expanded my question to my actual problem. Thanks. @Abhishek yes, maybe `yield` would work, but sincerely I am not very familiar with iterables and yield's and these parts of Python. – user11291 Apr 12 '14 at 12:16

1 Answers1

1

You are overcomplicating things. Just do what you were doing as (I suppose you could convert it to how you are showing it with tuple(my_list) but it is unnecessary):

return my_list

This is all you need to do because when you call that function that takes an undefined number of parameters, you can just call it as such:

function_with_undefined_number_of_params(*foo())

The * unpacks the returned list into separate arguments.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Thanks, but, and correct me if I am wrong, this would return a single tuple with all the elements inside, so if I do bar = foo(), bar would contain all the elments inside a tuple. And I need bar[0]=1, bar[1]=2 and so on. Hope I am clear, though. – user11291 Apr 12 '14 at 12:00
  • No wait, you are right. I'll recheck and see if this is solves my little problem here. – user11291 Apr 12 '14 at 12:04
  • @user11291 Great, I'm glad I could help. If I have resolved your issue, feel free to [accept my answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – anon582847382 Apr 12 '14 at 12:08
  • I am confused, the fucntion that returns my_list is foo() or function_with_undefined_number_of_params? – Eduardo EPF Mar 18 '21 at 13:29