user
How to convert an array to a coma separated string in Python?
alphonsio

The simplest option is to use the .join() method and the map() function:

arr = [1, 2, 3, 4, 5]
result = ",".join(map(str, arr))

In Python, you can convert an array (or list) to a comma-separated string using the join() method. Here are different ways to do it:

Basic Method (for a list of strings or numbers)

arr = [1, 2, 3, 4, 5]
result = ",".join(map(str, arr))
print(result)  # Output: "1,2,3,4,5"

Explanation:

  1. map(str, arr): Converts each element to a string.
  2. ",".join(...): Joins the elements with a comma.

Handling a List with Different Data Types

If your list contains mixed data types (e.g., numbers, strings, None, booleans), you can handle it like this:

arr = [1, "hello", None, True, 3.5]
result = ",".join(map(str, arr))
print(result)  # Output: "1,hello,None,True,3.5"

Using str.join() with a List of Strings

If the list already contains only strings, join() can be used directly:

arr = ["apple", "banana", "cherry"]
result = ",".join(arr)
print(result)  # Output: "apple,banana,cherry"
---

Using List Comprehension (Alternative)

arr = [1, 2, 3, 4, 5]
result = ",".join(str(x) for x in arr)
print(result)  # Output: "1,2,3,4,5"

This method avoids map() and is more readable for some developers.