Python - Print list without brackets and quotes


Python - Print list without brackets and quotes

When you print a list with string elements to console output in Python, quotes appear around string elements in the list, and brackets appear surrounding the list

To print list without brackets and quotes 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 comma.

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 surrounding the string elements, and no brackets surrounding the list.

apple, banana, 100, 200

Steps to print list without brackets and quotes in Python

  1. Given a list in x.
  2. Create an iterable which applies str() function to each element in the list x.
map(str, x)
  1. Join the elements in the iterable with the comma character followed by single space ", " as separator string using string join() method.
", ".join(map(str, x))
apple, banana, 100, 200

This is what we needed of the list to print to the output, without brackets and quotes.

Program

The complete program to print the given list without brackets and quotes to standard output is given below.

In the following program, print_list() function takes a list and prints the list without brackets and quotes.

Python Program

# Custom function to print list without brackets and quotes
def print_list(x):
    x_str = ", ".join(map(str, x))
    print(x_str)

# Given list
x = ['apple', 'banana', 100, 200]

print_list(x)

Output

apple, banana, 100, 200

There you have it. The list has been printed to output without brackets and quotes.

Summary

In this tutorial, we have seen how to print a given list without brackets and quotes, to standard output, using str() built-in function, map() built-in function, and string join() method, with example program.