How to remove square brackets from list in Python?


Question

LIST = ['Python','problem','whatever']
print(LIST)

When I run this program I get

[Python, problem, whatever]

Is it possible to remove that square brackets from output?

1
32
5/14/2016 10:35:21 PM

Accepted Answer

You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list aren't strings, you can convert them to string using either repr (if you want quotes around strings) or str (if you don't), like so:

LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'foo', 3.5, {'hello': 'bye'}
65
11/3/2012 9:23:09 AM

Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon