0

What would be the cleanest way to do comma separated printing on python for a list.

I have list: [1,2,3,4]

I need: "1, 2, 3, 4"
Masa Hu
  • 127
  • 13

4 Answers4

1

You can try to use map to apply str method to all the items to convert int to str and then use join method to concatenate the list:

string.join

Concatenate a list or tuple of words with intervening occurrences of sep.

a=[1,2,3,4]

print ",".join(map(str,a))

Output:

1,2,3,4
McGrady
  • 10,869
  • 13
  • 47
  • 69
1

The only unusual part is the ..., which str and repr both unfortunately turn into 'Ellipsis'. The other answers don't handle it correctly, but this one does:

>>> a = [1, 2, 3, 4, ...]
>>> print(', '.join('...' if x is ... else str(x) for x in a))
1, 2, 3, 4, ...

Edit: This is for the original question, before it was changed (though it still works).

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

You can do something on this line.

mylist = [1,2,3,4,5] 
m = map(str, mylist) # map function to convert each item in the list to a string 
j = ', '.join(m) # join to combine those strings with ', '
print (j)
Ajay
  • 775
  • 5
  • 19
0

Assuming you don't actually have ... and don't actually want to print the quotes:

>>> a = [1, 2, 3, 4]
>>> print(*a, sep=', ')
1, 2, 3, 4

Or less clean:

>>> print(str(a)[1:-1])
1, 2, 3, 4
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107