49

Consider this Python code for printing a list of comma separated values

for element in list:
    print element + ",",

What is the preferred method for printing such that a comma does not appear if element is the final element in the list.

ex

a = [1, 2, 3]
for element in a
  print str(element) +",",

output
1,2,3,
desired
1,2,3
codeforester
  • 39,467
  • 16
  • 112
  • 140
Mike
  • 58,961
  • 76
  • 175
  • 221
  • 3
    Possible duplicate of [How would you make a comma-separated string from a list?](http://stackoverflow.com/questions/44778/how-would-you-make-a-comma-separated-string-from-a-list) – Enamul Hassan Aug 13 '16 at 09:21

8 Answers8

110
>>> ','.join(map(str,a))
'1,2,3'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • How do I use this with a field of an object? so instead of "a" I would have "a.name" for example? – Boyen Sep 07 '16 at 14:54
  • 2
    A little explanation would be nice, you answer purely contains code. – Shayan Sep 27 '20 at 14:37
  • @Shayan this is a continuation of OP's question. `a` is the list/array of 1,2, and 3. The code in this answer converts that list into a string that is comma delimited `'1,2,3'` see https://docs.python.org/3/library/stdtypes.html#str.join – Brian W Jul 25 '23 at 20:26
16

It's very easy:

print(*a, sep=',')

Print lists in Python (4 Different Ways)

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ali Asadi
  • 161
  • 1
  • 2
15

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!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • enumerate is good, but in OP's case, a simple join is enough. – ghostdog74 Mar 08 '10 at 05:06
  • 1
    Sure, that's what I started with (giving the genexp at a time when other answers had maps, listcomps, or no conversion-to-string) -- have you _seen_ the first paragraph of this answer, perchance?-) First-time and last-time switches are more versatile, and no other answer even mentioned them, so I chose to point them out too, of course (including the fact that they're best done via enumerate). – Alex Martelli Mar 08 '10 at 05:13
  • Looking at your answer and looking at ghostdog's answer, I'm wondering something. Does a list comprehension use more memory than map will from his example, but is map() slower than a LH? BTW, I recommended your book to somebody who emailed me for help on Python :) – orokusaki Mar 10 '10 at 04:33
  • @orokusaki, memory consumption's the same for map and listcomp (lower for genexp, which is what I use instead); genexp is typically slightly slower (if you have oodles of physical memory available, that is, otherwise the memory consumption of listcomp and map damages their performance), and map sometimes even faster than listcomp (unless it involves using a lambda, which slows it down). None of these performance issues is at all a biggie, unless you must watch your memory footprint for whatever reason, in which case genexp's parsimony in memory *can* be a biggie;-). – Alex Martelli Mar 10 '10 at 04:46
  • @Ah, I didn't even notice that you left off the brackets. I see now. I like the idea of using a genexp. I'd rather let my users wait the extra .1 milliseconds than decrease the number of concurrent requests I can handle by hogging memory. Not to mention that since I can't control the size of the iterable, somebody could really jam things up with the listcomp version. – orokusaki Mar 10 '10 at 17:13
4

There are two options ,

You can directly print the answer using print(*a, sep=',') this will use separator as "," you will get the answer as ,

1,2,3

and another option is ,

print(','.join(str(x) for x in list(a)))

this will iterate the list and print the (a) and print the output as

1,2,3
Midhunlal
  • 333
  • 2
  • 11
2

That's what join is for.

','.join([str(elem) for elem in a])
Tyler
  • 21,762
  • 11
  • 61
  • 90
  • 1
    `TypeError: sequence item 0: expected string, int found.` It doesn't work for his sample input. – Ponkadoodle Mar 08 '10 at 03:30
  • Right, sorry. It doesn't automatically convert the ints to strings. Fixed with a nifty list comprehension. – Tyler Mar 08 '10 at 03:48
  • 7
    Don't use a list comprehension. Take out the `[]`s and it'll make a generator, which will work just as well without creating a (potentially large) unnecessary temporary list. – Chris Lutz Mar 08 '10 at 03:49
-1
print ','.join(a)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
-2
 def stringTokenizer(sentense,delimiters):
     list=[]
     word=""
     isInWord=False
     for ch in sentense:
         if ch in delimiters:
             if isInWord: # start ow word
                 print(word)
                 list.append(word)
                 isInWord=False
         else:
             if not isInWord: # end of word
                 word=""
                 isInWord=True
             word=word+ch
     if isInWord: #  end of word at end of sentence
             print(word)
             list.append(word)
             isInWord=False
     return list

print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))

A K
  • 714
  • 17
  • 39
-3
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343