Python - Print List without quotes and commas
Python - Print list without quotes and commas
When you print a list with string elements to console output in Python, quotes appear around string elements in the list, and commas between the elements in the list.
To print list without quotes and commas in Python, write a custom function that takes a list as argument, converts each of the list element to string, then join all the elements in the list with a single space, 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 quotes and commas in the printed output.
[apple banana 100 200]
Steps to print list without quotes and commas in Python
- Given a list in x.
['apple', 'banana', 100, 200]
- Create an iterable which applies str() function to each element in the list x.
map(str, x)
- Join the elements in the iterable with a single space
" "
as separator string using string join() method.
" ".join(map(str, x))
apple banana 100 200
- The join() method returns the required string to print to output. You may print it using print() built-in function.
Program
The complete program to print the given list without quotes around any elements in it, and without commas between the elements, to standard output is given below.
In the following program, print_list_without_quotes() function takes a list and prints the list without quotes and commas.
Python Program
# Custom function to print list without quotes
def print_list_without_quotes(x):
print("[" + ", ".join(map(str, x)) + "]")
# Given list
x = ['apple', 'banana', 100, 200]
print_list_without_commas(x)
Output
[apple, banana, 100, 200]
There you have it. The list has been printed to output without quotes and commas.
Summary
In this tutorial, we have seen how to print a given list without quotes and commas, to standard console output, using str() built-in function, map() built-in function, and string join() method, with example program.