Python - Join List with Comma
Python - Join list with comma
To join a given list of elements with comma separator into a Python string, call string join() method on comma character ",", and pass the given list as argument to the join() method. The join() method returns a new string created by joining the elements in the list with the comma character in between them.
1. Joining list of strings with comma using string join() method
Consider that we are given a list of string elements, and we have to join them into a string with comma as separator between the elements.
Steps
- Given a list of strings in my_list.
- Call string join() method on comma character (taken as string literal), and pass the list as argument.
','.join(my_list)
- The join() method returns a string created by joining the elements in the list with the comma character in between them. Assign the returned value to a variable, say joined_str.
- You may print the returned string to the standard output using print() statement.
Program
The complete program to join the elements of a list with comma character as separator.
Python Program
# Given a list
my_list = ['apple', 'banana', 'cherry']
# Join list of strings with comma
joined_str = ','.join(my_list)
print(joined_str)
Output
apple,banana,cherry
2. Joining list of numbers with comma using string join() method
In this example, we shall take a list of numbers, and join the numbers in the list with comma separator between the elements.
join() method works only on the string elements. Therefore, to join the numbers in a list, you have to convert them to strings. In the following program, we have used list comprehension to convert the numbers into strings.
Python Program
# Given a list
my_list = [10, 20, 30, 40, 50]
# Join list of numbers with comma
joined_str = ','.join([ str(x) for x in my_list])
print(joined_str)
Output
10,20,30,40,50
Summary
In this tutorial, we have seen how to join a list of elements with comma separator using string join() method, with examples.