Kodeclik Blog

How to print a Python list without brackets and commas

Sometimes when you are dabbling with Python lists, you might wish to print a list without the annoying brackets and commas that Python by default prints. For instance, consider the following code:
The output is:
Let us figure out how to get rid of the (square) brackets, commas, and even the quotes if you need so! There are at least four different ways to do so!

Method 1: Use the print function with a sep argument

The first approach is to use the print function, like above, but with a “sep” argument specifying the separator (in our case, we do not wish for any separator):
The output will be:
as desired.

Method 2: Use a join method to concatenate after converting all parts to strings

In our second approach, we use the map function to convert all arguments to strings and then use the join function to concatenate them giving the empty string as the starting point for the join function:
The output is again:

Method 3: Use a traditional for loop and the end argument to avoid newlines

This approach is a bit traditional but illustrates how we can use a for loop with an end argument to achieve the same effect:
The output is:
Note that with this approach we do not print a newline at the end of all the printing: the cursor will be positioned just after the “r” in our string.

Method 4: Use the translate method

The translate method allows you to make modifications to a string, where some specified characters are replaced with the character described in a dictionary, or in a mapping table. For this purpose, we first create a dictionary and then use this dictionary in the translate() method:
Here the codes 32, 39, 44, 91, and 93 refer to the characters for space, starting and closing brackets, left square bracket, and right square bracket respectively. All these characters are mapped to ‘None’ in the dictionary which is then used in the translate method. The output is as before:
You have learnt four different ways to “sanitize” a list by removing brackets, commas, and spaces before printing it. Which one is your favorite?
If you liked the list manipulations here, checkout our companion blogpost on how to split a Python list into sublits of different, specified, sizes!
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.