Last modified: Sep 20, 2023 By Alexander Williams

Python List to String with Commas Examples

Example 1: Basic List to Comma-Separated String


# Initialize a list of words
my_list = ["apple", "banana", "cherry"]

# Convert the list to a comma-separated string
result = ", ".join(my_list)

# Print the resulting string
print("Result:", result)
    

Output:


Result: apple, banana, cherry
    

Example 2: Numeric List to Comma-Separated String


# Initialize a list of numbers
my_list = [1, 2, 3, 4, 5]

# Convert the list of numbers to a comma-separated string
result = ", ".join(map(str, my_list))

# Print the resulting string
print("Result:", result)
    

Output:


Result: 1, 2, 3, 4, 5
    

Example 3: Using List Comprehension for Custom Formatting


# Initialize a list of names
my_list = ["Alice", "Bob", "Charlie"]

# Use list comprehension for custom formatting with commas
result = ", ".join(f"Name: {name}" for name in my_list)

# Print the resulting string
print("Result:", result)
    

Output:


Result: Name: Alice, Name: Bob, Name: Charlie
    

Example 4: Joining List of Integers as a Comma-Separated String


# Initialize a list of integers
my_list = [10, 20, 30, 40, 50]

# Convert the list to a comma-separated string
result = ", ".join(map(str, my_list))

# Print the resulting string
print("Result:", result)
    

Output:


Result: 10, 20, 30, 40, 50
    

Example 5: Using `str.join()` with List of Mixed Types


# Initialize a list with mixed types
my_list = [1, "apple", 2.5, True]

# Convert the list to a comma-separated string
result = ", ".join(map(str, my_list))

# Print the resulting string
print("Result:", result)
    

Output:


Result: 1, apple, 2.5, True
    

Example 6: List of Strings with Commas in Elements


# Initialize a list of strings with commas
my_list = ["apple, banana", "cherry, date", "fig"]

# Convert the list to a comma-separated string
result = ", ".join(my_list)

# Print the resulting string
print("Result:", result)
    

Output:


Result: apple, banana, cherry, date, fig
    

Example 7: Using List Slicing for Custom Separation


# Initialize a list of words
my_list = ["python", "is", "awesome"]

# Add a custom separator between elements
result = " >> ".join(my_list)

# Print the resulting string
print("Result:", result)
    

Output:


Result: python >> is >> awesome
    

Example 8: Empty List to Comma-Separated String


# Initialize an empty list
my_list = []

# Convert the empty list to an empty string
result = ", ".join(my_list)

# Print the resulting string (empty)
print("Result:", result)
    

Output:


Result:
    

Example 9: Using List of Tuples and Custom Formatting


# Initialize a list of tuples
my_list = [("Alice", 25), ("Bob", 30), ("Charlie", 28)]

# Format each tuple as "Name (Age)" and join with commas
result = ", ".join(f"{name} ({age})" for name, age in my_list)

# Print the resulting string
print("Result:", result)
    

Output:


Result: Alice (25), Bob (30), Charlie (28)