Convert a List of Integers to a Comma-Separated String in Python

Convert a list of integers into a single comma-separated string using a generator expression and str.join.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

7 lines
Python 3.9+
def ints_to_comma_string(numbers):
    return ",".join(str(num) for num in numbers)

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    result = ints_to_comma_string(numbers)
    print(result)

Output

stdout
1,2,3,4,5

How it works

The function ints_to_comma_string uses a generator expression to convert each integer to a string, then joins them with a comma separator. str.join expects an iterable of strings, so converting each number to str first is essential. This approach is memory-efficient because the generator yields one string at a time without creating an intermediate list. The if __name__ == "__main__" guard ensures the example runs only when the script is executed directly.

Common mistakes

  • Forgetting to convert integers to strings before calling join, causing a TypeError.
  • Using a list comprehension instead of a generator, which is slightly less memory-efficient for large lists.
  • Joining with spaces (e.g., ', ') when a plain comma is expected.

Variations

  1. Use `', '.join(map(str, numbers))` to avoid an explicit generator.
  2. For a list of integers as a single string with brackets, use `str(numbers)` instead.

Real-world use cases

  • Formatting database query results into a CSV-like string for export or logging.
  • Converting a list of user IDs into a single parameter for an API request or SQL IN clause.
  • Building a comma-separated list of item codes to include in an email or notification message.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.