Reputation: 708
Just new to Python. And try to learn how I can print a list of tuples side by side. Let's say I have a list of tuple with a format of:
myList =[('05', 5), ('08', 3), ('12', 5)]
And I would like to have an output like:
05 5
08 3
12 5
without single quotes. What is the best way to do that?
Upvotes: 0
Views: 12646
Reputation: 7504
You can unpack the values in a iterable, which works for more than two elements in tuple as well.
myList =[('05', 5, 3), ('08', 3), ('12', 5)]
for a in myList:
print(*a, sep=" ")
You can use a different seperator, space is the default one.
Upvotes: 0
Reputation: 476584
python-3.x adds automatically a space between elements in the print statement. In python-3.x, we can use iterable unpacking:
for row in myList:
print(*row)
producing:
>>> for row in myList:
... print(*row)
...
05 5
08 3
12 5
In case you want another separator (e.g. a pipe |
), you can set the sep
attribute:
for row in myList:
print(*row, sep='|')
this produces:
>>> for row in myList:
... print(*row,sep='|')
...
05|5
08|3
12|5
This approach can handle any number of elements in the tuple (e.g. a list of 3-tuples), and in case the tuples have different lengths (e.g. [(1,2),(3,4,5)]
), it will print the 3-tuples with three columns and the 2-tuples with two columns.
Upvotes: 1
Reputation: 16733
Just loop over it.
for value in myList:
print(value[0], value[1])
Upvotes: 2
Reputation: 71451
You can use unpacking, a feature in Python3:
myList =[('05', 5), ('08', 3), ('12', 5)]
for a, *b in myList:
print(a, ' '.join(map(str, b)))
This way, if you have more than three elements in the tuple, you will not have an ToManyValuesToUnpack
error raised.
Output:
05 5
08 3
12 5
For example:
myList =[('05', 5, 10, 3, 2), ('08', 3, 4), ('12', 5, 2, 3, 4, 5)]
for a, *b in myList:
print(a, ' '.join(map(str, b)))
Output:
05 5 10 3 2
08 3 4
12 5 2 3 4 5
Upvotes: 2
Reputation: 36662
It is rather simple, you can, for instance, unpack the tuple in a for loop:
myList =[('05', 5), ('08', 3), ('12', 5)]
for a, b in myList: # <-- this unpacks the tuple like a, b = (0, 1)
print(a, b)
05 5
08 3
12 5
Upvotes: 8
Reputation: 2301
If you want a simple solution for a fixed tuple size of two, then this works:
for tup in myList:
print(tup[0], tup[1])
If, though, you would prefer to print varying length tuples without changing your code, you could do something like this:
for tup in myList:
print(' '.join(map(str,tup)))
Upvotes: 0