54
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?

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
Gregor Gajič
  • 643
  • 1
  • 5
  • 6
  • I suggest `map` instead of `str(i) for i in LIST` - `map` is C code so it's faster – yedpodtrzitko Nov 03 '12 at 09:38
  • list comprehension is actually faster than map in Python2 because it does not create a stack frame that is computationally expensive. map creates it. But this behavior is problematic that the variable in the list comprehension could leak due to rebinding if a variable with the same name was declared before. The list comprehension in Python3 does not exhibit such problem because it's changed to create a stack frame to be consistent with generator expressions. – Kenji Noguchi Feb 09 '17 at 04:02

4 Answers4

101

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'}
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
44

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.

Vicent
  • 5,322
  • 2
  • 28
  • 36
23

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
16
def listToStringWithoutBrackets(list1):
    return str(list1).replace('[','').replace(']','')
lahjaton_j
  • 805
  • 7
  • 13