JavaRed
JavaRed

Reputation: 708

How print list of tuples side by side

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

Answers (7)

bhansa
bhansa

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

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

adds automatically a space between elements in the print statement. In , 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

hspandher
hspandher

Reputation: 16733

Just loop over it.

for value in myList:
    print(value[0], value[1])

Upvotes: 2

Ajax1234
Ajax1234

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

Reblochon Masque
Reblochon Masque

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)

output:

05 5
08 3
12 5

Upvotes: 8

Evan
Evan

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

englealuze
englealuze

Reputation: 1663

for i, j in myList:
    print(i, j)

Upvotes: 0

Related Questions