Reputation:
I have a piece of code that does everything I need it to do and now I am making it look better and refining it. When I print the outcome, I find that the list in the statement is in square brackets and I cannot seem to remove them.
Upvotes: 2
Views: 18554
Reputation: 316
Why don't you display the elements in the list one by one using the for loop instead of displaying an entire list at once like so:
# l - list
for i in range(0, len(l)):
print l[i],
Upvotes: 1
Reputation: 304
You could do smth like this:
separator = ','
print separator.join(str(element) for element in myList)
Upvotes: 1
Reputation: 20336
You can use map()
to convert the numbers to strings, and use " ".join()
or ", ".join()
to place them in the same string:
mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5
You could also just take advantage of the print()
function:
mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5
Note: In Python2, that won't work because print
is a statement, not a function. You could put from __future__ import print_function
at the beginning of the file, or you could use import __builtin__; getattr(__builtin__, 'print')(*mylist)
Upvotes: 5
Reputation: 149806
If print
is a function (which it is by default in Python 3), you could unpack the list with *
:
>>> L = [3, 5]
>>> from __future__ import print_function
>>> print(*L)
3 5
Upvotes: 1
Reputation: 644
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list are not strings, you can convert them to string using either repr() or str() :
LIST = [1, "printing", 3.5, { "without": "brackets" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'printing', 3.5, {'without': 'brackets'}
Upvotes: 1