Search code examples
pythonstringlist-comprehension

How to form a string using list comprehension?


I am trying to form a string using a list.

If the list only has a single element e.g. l = [10] then the string should be 10.

If there are multiple elements e.g. l = [10,20,30] then the string should be 10,20,30.

I tried but it always appends extra , at the end.

"".join("%s," % x for x in l)

This produces 10, and 10,20,30, for the above lists.


Solution

  • Just use the following:

    ','.join(str(n) for n in l)