Print list without brackets in a single row

print(', '.join(names))

This, like it sounds, just takes all the elements of the list and joins them with ', '.


Here is a simple one.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

the star unpacks the list and return every element in the list.


General solution, works on arrays of non-strings:

>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'

If the input array is Integer type then you need to first convert array into string type array and then use join method for joining with , or space whatever you want. e.g:

>>> arr = [1, 2, 4, 3]
>>> print(", " . join(arr))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> sarr = [str(a) for a in arr]
>>> print(", " . join(sarr))
1, 2, 4, 3
>>>

Direct using of join which will join the integer and string will throw error as show above.

Tags:

Python

List