How to Print a List without Commas and Brackets in Python?

Estimated read time 2 min read

To print a list without commas and brackets in Python, you can use a loop to iterate through each element in the list and print each element using the print() function, separated by a space.

Here is an example:

my_list = [1, 2, 3, 4, 5]

for element in my_list:
    print(element, end=" ")

In this example, we have a list called my_list with five integer elements. We use a for loop to iterate through each element in the list, and then print each element using the print() function. We use the end parameter to separate the elements with a space instead of a newline character.

The output of this code will be:

1 2 3 4 5

Note that you can customize the separator between elements by changing the value of the end parameter. For example, you can use end="," to separate the elements with a comma instead of a space. If you want to remove any leading or trailing spaces from the output, you can use the strip() method to remove them before printing the output, like this:

my_list = [1, 2, 3, 4, 5]

output_string = ""
for element in my_list:
    output_string += str(element) + " "

print(output_string.strip())

In this example, we create an empty string called output_string and use a for loop to iterate through each element in the list. We append each element to the string, followed by a space character. Finally, we use the strip() method to remove any leading or trailing spaces from the output string before printing it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply