I have a function which returns a large set of integer values as a tuple. For example:
def solution():
return 1, 2, 3, 4 #etc.
I want to elegantly print the solution without the tuple representation. (i.e. parentheses around the numbers).
I tried the following two pieces of code.
print ' '.join(map(str, solution())) # prints 1 2 3 4
print ', '.join(map(str, solution())) # prints 1, 2, 3, 4
They both work but they look somewhat ugly and I'm wondering if there's a better way of doing this. Is there a way to "unpack" tuple arguments and pass them to the print statement in Python 2.7.5?
I would really love to do something like this:
print(*solution()) # this is not valid syntax in Python but I wish it was
kind of like tuple unpacking so that it's equivalent to:
print sol[0], sol[1], sol[2], sol[3] # etc.
Except without the ugly indexes. Is there any way to do that?
I know this is a stupid question because I'm just trying to get rid of parentheses but I was just wondering if there was something I was missing.
print(*solution()) actually can be valid on python 2.7, just put:
from __future__ import print_function
On the top of your file.
You could also iterate through the tuple:
for i in solution():
print i,
This is equivalent to:
for i in solution():
print(i, end= ' ')
If you ever use Python 3 or the import statement above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With