join()Function to Print Lists Without Square Brackets in Python
- Use the Unpack Method to Print Lists Without Square Brackets in Python
strFunction to Print Lists Without Square Brackets
This tutorial will introduce how to print a list without showing these square brackets.
join() Function to Print Lists Without Square Brackets in Python
join() function takes all the elements from an iterable object, like a list, and returns a string with all elements separated by a character specified with the function. Using this method, we can remove the square brackets from a list and separate the elements using a comma or whichever character we desire. The following code snippet implements this.
lst = ['x','y','z'] print(','.join(lst))
Note that this method only works with a list containing strings and fails with a list of integer or float values.
Use the Unpack Method to Print Lists Without Square Brackets in Python
* operator in Python can be used to unpack objects. It unpacks all the elements from a list and prints it without the square brackets as shown below.
lst = ['x','y','z'] print(*lst, sep = ',')
We separate the elements using the character specified in the
sep parameter and can be removed if desired.
str Function to Print Lists Without Square Brackets
In this method, we convert a list to a string using the
str() function and then remove the first and last characters from this string that are the square brackets. The following code shows how.
lst = [1,2,3] lst_str = str(lst)[1:-1] print(lst_str)
1, 2, 3
Note that this method can work with a list containing integers or floats values also.
Another way in which we can use this function is to convert each element of a list to a string. We can then proceed to remove the brackets using the
join() function as discussed earlier. For example,
lst = [1,2,3] lst_new = [str(a) for a in lst] print("," . join(lst_new))
In the above code, we convert all the elements from the
lst to string values using the
str function and create a new list,
lst_new, using the list comprehension method.