How to "properly" print a list?

This is simple code, so if you are new you should understand it easily enough.

mylist = ["x", 3, "b"]
for items in mylist:
    print(items)

It prints all of them without quotes, like you wanted.


If you are using Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".


Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

Tags:

Python

String