5

I have 3 arrays, a1, a2, a3

I would like to return all three of them at once.

I have

return a1, a2, a3 but it returns them all on the same line, I was wondering how I would return them each on a new line

2
  • 5
    What do you mean by "on the same line" or "on a new line"? Commented Nov 19, 2012 at 5:18
  • If you want to see the arrays each in it's own line, use pprint module: import pprint; pprint.pprint(your_func()). If it's about assignment then John's anwer is valid. Commented Nov 19, 2012 at 5:40

5 Answers 5

11

Do you mean like this?

>>> def f():
...   a1 = [1, 2, 3]
...   a2 = [4, 5, 6]
...   a3 = [7, 8, 9]
...   return a1, a2, a3
... 
>>> f()
([1, 2, 3], [4, 5, 6], [7, 8, 9])

You can unpack the return value like this

>>> b1, b2, b3 = f()
>>> b1
[1, 2, 3]
>>> b2
[4, 5, 6]
>>> b3
[7, 8, 9]

Or print it on 3 lines like this

>>> print "\n".join(str(x) for x in f())
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Sign up to request clarification or add additional context in comments.

Comments

1

Are you asking to be able to do

return a1
return a2
return a3

instead of

return a1, a2, a3

???

If so, I am sorry, but you cannot do that. When you use the return a1, a2, a3 you are actually returning one thing, a tuple of 3 lists. Execution of a return statement will return out of the current scope/context to the caller. If this is not what you are trying to do, please explain a little more clearly what you are after.

1 Comment

If he wraps the returned tuple with parens he will be able to write each element in it's line. The question is vague and I'm guessing, maybe this is what he's after?
1

You can only return once from a method. However, the data can still be accessed on separate lines.

def dosomething():
    ...
    return a1, a2, a3

myTuple = dosomething()
first = myTuple[0]
second = myTuple[1]
third = myTuple [2]

Comments

0

if a1, a2 ,a3 are same length, you may try this

a1 = [1, 2, 3]
a2 = [4, 5, 6]
a3 = [7, 8, 9]
[ (a1[x],a2[x],a3[x]) for x in range(len(a1)) ]

>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Comments

0

I think you're treating an array like a string - arrays don't span "lines" per say.

Maybe this is what you're looking for; if I understood correctly.

 return str(a1)+'\n'+str(a2)+'\n'+str(a3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.