Python - Print List Without Commas
Python - Print list without commas
When you print a list to console output in Python, commas appear between the elements in the list.
To print list without commas in Python, write a custom function that takes a list as argument, joins all the elements in the list with single space as separator between the elements, and enclose the resulting string in square brackets.
For example, consider the following list.
x = ['apple', 'banana', 100, 200]
When you print this list to output using print() built-in function, you would get the following output.
['apple', 'banana', 100, 200]
But, our requirement is that there should not be commas between the elements in the list.
['apple' 'banana' 100 200]
Just the commas removed between the elements. Rest all same.
Steps to print list without commas in Python
The following is a step by step process to print the given list without commas in Python. Also, intermediate results have been given after the code, so that we understand what is happening with an example.
- Given a list in x.
x = ['apple', 'banana', 100, 200]
- Use list comprehension and convert each of the element in the list to a string.
[str(item) for item in x]
['apple', 'banana', '100', '200']
- We have to modify this list comprehension to surround the string elements with single quotes. Place single quotes around the element if the element is an instance of str class, or else just the item.
[f"'{item}'" if isinstance(item, str) else str(item) for item in x]
['\'apple\'', '\'banana\'', '100', '200']
This step is to preserve the quotes surrounding the string elements in the list when printed to output.
- Join the elements of the above list with single space as separator using string join() method, and concatenate opening and closing square brackets surrounding the string using string concatenation.
"[" + " ".join(items_str) + "]"
['apple' 'banana' 100 200]
- You may print this string to output using print() built-in function.
Program
The complete program to print the given list without commas between the elements to standard output is given below.
In the following program, print_list_without_commas() function takes a list and prints the list without commas.
Python Program
# Custom function to print list without commas
def print_list_without_commas(x):
items_str = [f"'{item}'" if isinstance(item, str) else str(item) for item in x]
print("[" + " ".join(items_str) + "]")
# Given a list of strings
my_list = ['apple', 'banana', 100, 200]
print_list_without_commas(my_list)
Output
['apple' 'banana' 100 200]
There you have it. The list has been printed to console output without commas.
Summary
In this tutorial, we have seen how to print a given list without commas between the elements, to standard output, using str() built-in function, list comprehension with if else, string join() method, string concatenation, and print() built-in function, with an example program.