In this tutorial, we will learn how to add a comma to a list using Python. Lists are one of the most used and versatile data structures in Python, which can store multiple values of different data types. While working with lists, it is a common requirement to separate list items with a comma to make the output more readable.
Step 1: Create a list
First, let’s create a list. For example, we will create a list of names:
1 |
names = ['John', 'Alice', 'Bob', 'Eve'] |
Here, we have a list of strings containing four names.
Step 2: Convert the list into a string with the join()
method
To add a comma between list elements, we will use the join()
method provided by Python. The join()
method combines the elements of a list separated by a specified string. Here, we will use a comma followed by a space, i.e., ', '
.
1 |
names_string = ', '.join(names) |
This will create a string containing the list elements, separated by a comma and space.
Step 3: Print the resulting string
Now, let’s print the names_string
:
1 |
print(names_string) |
Output:
John, Alice, Bob, Eve
As you can see, the output contains the names in the list, separated by a comma and space.
Full code:
1 2 3 |
names = ['John', 'Alice', 'Bob', 'Eve'] names_string = ', '.join(names) print(names_string) |
Conclusion
In this tutorial, we have learned how to add a comma between list elements in Python using the join()
method. This is a handy technique for formatting the output of a list in a more readable way.