Print all items in a list with a delimiter
Asked Answered
H

8

50

Given a Python list, what is the preferred way to print it with comma delimiter/separator, and no intervening spaces, and no trailing comma at the end, after the last element:

I tried:

a = [1, 2, 3]
for element in a:
  print str(element) + ",", # old Python 2 syntax

output
1,2,3,
desired
1,2,3
Hanahanae answered 8/3, 2010 at 3:25 Comment(3)
Possible duplicate of How would you make a comma-separated string from a list?Pilcher
Note you don't want whitespace between the list elements, so not 1, 2, 3, which is what you would get from simply doing print(a)Rumelia
In Python 3, for element in a: print(str(element), sep=',', end='') only gives you 123 without commas, because print can't see the whole thing is a list; like print(a) would, but print(a, sep=',') gives you [1, 2, 3] with the unwanted spaces (and with brackets).Rumelia
W
114
>>> ','.join(map(str,a))
'1,2,3'
Wildwood answered 8/3, 2010 at 3:27 Comment(3)
How do I use this with a field of an object? so instead of "a" I would have "a.name" for example?Finny
A little explanation would be nice, you answer purely contains code.Maunder
@Maunder 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 docs.python.org/3/library/stdtypes.html#str.joinInkling
T
19

It's very easy:

print(*a, sep=',')

Print lists in Python (4 Different Ways)

Teel answered 12/6, 2019 at 1:42 Comment(0)
C
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!

Cutpurse answered 8/3, 2010 at 3:42 Comment(5)
enumerate is good, but in OP's case, a simple join is enough.Wildwood
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).Cutpurse
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 :)Saarinen
@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;-).Cutpurse
@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.Saarinen
H
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
Homy answered 6/10, 2017 at 16:16 Comment(0)
C
2

That's what join is for.

','.join([str(elem) for elem in a])
Cuprum answered 8/3, 2010 at 3:26 Comment(3)
TypeError: sequence item 0: expected string, int found. It doesn't work for his sample input.Pulpiteer
Right, sorry. It doesn't automatically convert the ints to strings. Fixed with a nifty list comprehension.Cuprum
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.Estivation
C
-1
print ','.join(a)
Chime answered 8/3, 2010 at 3:26 Comment(3)
join doesn't automatically convert ints to strings, so this won't work.Tantalite
@musicfreak Does this seem silly to you that it doesn't str() it automatically? After all, ''.join() is a String method. I wonder why it doesn't do it for free.Saarinen
@orokusaki: It goes against the precept "Explicit is better than implicit".Chime
T
-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"привет парни! я вам стихами, может быть, еще отвечу",", !"))

Tormentil answered 15/8, 2016 at 10:15 Comment(1)
I've replaced sample string 'cause it's too offensive for russian spoken.Accouter
W
-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'
Wildwood answered 8/3, 2010 at 5:15 Comment(1)
i have to assume you're kiddingHanahanae

© 2022 - 2024 — McMap. All rights reserved.