Print list without brackets in a single row

Python Programming

Question or problem about Python programming:

I have a list in Python
e.g.

names = ["Sam", "Peter", "James", "Julian", "Ann"]

I want to print the array in a single line without the normal ” []

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

Will give the output as;

["Sam", "Peter", "James", "Julian", "Ann"]

That is not the format I want instead I want it to be like this;

Sam, Peter, James, Julian, Ann

Note: It must be in a single row.

How to solve the problem:

Solution 1:

print(', '.join(names))

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

Solution 2:

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.

Solution 3:

General solution, works on arrays of non-strings:

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

Solution 4:

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 "", line 1, in 
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.

Solution 5:

There are two answers , First is use ‘sep’ setting

>>> print(*names, sep = ', ')

The other is below

>>> print(', '.join(names))

Hope this helps!