Jika
Jika

Reputation: 1584

How to print a list of tuples without commas in Python?

I have two lists in python.

a = [1, 2, 4, 8, 16]
b = [0, 1, 2, 3, 4]

and a third list c that is the zip of them.

c = zip(a, b) 

or simply I have a list of tuples like this:

c = [(1, 0), (2, 1), (4, 2), (8, 3), (16, 4)]

I would like to print the list c without the commas after the parentheses. Is there a way to do this in Python?

I would like to print the list c like this:

[(1, 0) (2, 1) (4, 2) (8, 3) (16, 4)]

Upvotes: 1

Views: 2039

Answers (3)

Rafael Albert
Rafael Albert

Reputation: 445

print('[' + ' '.join([str(tup) for tup in c]) + ']')

Using a list comprehension to create a list of the tuples in string form. Those are then joined and the square brackets are added to make it look as you want it.

Upvotes: 3

Matt Cremeens
Matt Cremeens

Reputation: 5151

Would it be okay to create the final result as a string?

c_no_comma = ''
for element in c:
    c_no_comma += str(element) + ' '

c_no_comma = '[ ' + c_no_comma + ']'

Upvotes: 0

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

print('[%s]' % ' '.join(map(str, c)))

Prints:

[(1, 0) (2, 1) (4, 2) (8, 3) (16, 4)]

for your inputs.

You can basically take advantage of the fact that you're using the natural string representation of the tuples and just join with a space.

Upvotes: 3

Related Questions