Convert List to comma-separated string in Python

This tutorial will discuss about unique ways to convert list of integers to comma-separated string in Python.

Table Of Contents

Method 1: Using map() function

Apply the str() function on each integer in list using the map() function. Then join all those converted strings into a big string, and use a comma as delimeter. For this, use the join() method of string in Python. This way we can convert a list of integers to a comma-separated string.

Let’s see the complete example,

listOfNums = [11, 12, 13, 15, 18, 29]

# Convert list of integers to comma-separated string
strValue = ','.join(map(str, listOfNums))

print(strValue)

print(type(strValue))

Output

11,12,13,15,18,29
<class 'str'>

Here the map(str, listOfNums) function convrted the list of integers into a sequence of strings i.e.

Let’s see the complete example,

['11', '12', '13', '15', '18', '29']

Then we joined these strings using a comma as delimeter using the function ','.(sequence_of_strings).

Method 2: Using Generator expression

Iterate over all numbers in string using a for loop in generator expression, and for each number, converted it to string and yield it from generator expression. Then join all those converted strings into a single string using the join() function. The join() function will be called on a delimeter string i.e. comma, therefore all elements in string will be separated by a comma. This way list of integers will be converted to a comma-separated string.

Let’s see the complete example,

listOfNums = [11, 12, 13, 15, 18, 29]

# Convert list of integers to comma-separated string
strValue = ','.join(str(num) for num in listOfNums)

print(strValue)

print(type(strValue))

Output

11,12,13,15,18,29
<class 'str'>

Method 3: Using for loop

This is the most simplest solution. Create an empty string. Then loop over all integers in list using a for loop. During iteration, convert each integer to a string, and add them to the empty string along with a comma. This way list of integers will be converted to a comma-separated string.

Let’s see the complete example,

listOfNums = [11, 12, 13, 15, 18, 29]

strValue = ""

# Convert list of integers to comma-separated string
# Iterate over each element of list
for elem in listOfNums:
    # Check if string is empty
    if len(strValue) > 0:
        # If not then add element to string
        strValue = strValue + ',' + str(elem)
    else:
        strValue = str(elem)

print(strValue)
print(type(strValue))

Output

11,12,13,15,18,29
<class 'str'>

Summary

We learned about different ways to convert a list of integers into a comma-separated string in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top