The Python Oracle

Print list without brackets in a single row

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Print List Without Brackets In A Single Row
00:31 Accepted Answer Score 365
00:43 Answer 2 Score 126
00:56 Answer 3 Score 61
01:07 Answer 4 Score 29
01:34 Answer 5 Score 23
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/1117...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 367


print(', '.join(names))

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




ANSWER 2

Score 127


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.




ANSWER 3

Score 61


General solution, works on arrays of non-strings:

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



ANSWER 4

Score 29


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.