Python – Print List without Brackets and Commas

Python – Print list without brackets and commas

When you print a list to console output in Python, commas appear between the elements in the list, and brackets surrounding the whole list.

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

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, and there should not be brackets around the list.

'apple' 'banana' 100 200

Steps to print list without brackets and commas in Python

The following is a step by step process to print the given list without brackets and commas in Python. Also, intermediate results have been given after the code, so that we understand what is happening with an example.

  1. Given a list in x.
x = ['apple', 'banana', 100, 200]
  1. 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']
  1. 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.

  1. Join the elements of the above list with single space as separator using string join() method.
" ".join(items_str)
'apple' 'banana' 100 200
  1. You may print this string to output using print() built-in function.

Program

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

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

Python Program

# Custom function to print list without commas and brackets
def print_list(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(my_list)
Run Code Copy

Output

'apple' 'banana' 100 200

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

Summary

In this tutorial, we have seen how to print a given list without brackets and commas to standard console 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.

Related Tutorials

Code copied to clipboard successfully 👍