A ','.join
as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is
print ','.join(str(x) for x in a)
known as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:
for i, x in enumerate(a):
if i: print ',' + str(x),
else: print str(x),
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len()
(not for completely general ones):
for i, x in enumerate(a):
if i == len(a) - 1: print str(x)
else: print str(x) + ',',
this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
1, 2, 3
, which is what you would get from simply doingprint(a)
– Rumeliafor element in a: print(str(element), sep=',', end='')
only gives you123
without commas, becauseprint
can't see the whole thing is a list; likeprint(a)
would, butprint(a, sep=',')
gives you[1, 2, 3]
with the unwanted spaces (and with brackets). – Rumelia