How can I format a list to print each element on a separate line in python?
182,816
Solution 1
You can just use a simple loop: -
>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
print elem
10
12
14
Solution 2
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
Author by
user1825241
Updated on July 09, 2022Comments
-
user1825241 almost 2 years
How can I format a list to print each element on a separate line? For example I have:
mylist = ['10', '12', '14']
and I wish to format the list so it prints like this:
10 12 14
so the \n, brackets, commas and '' is removed and each element is printed on a separate line Thanks
-
inspectorG4dget over 11 yearsThis would actually work better than
str.join
which expects each element to be astr
. -
jeromej over 11 yearsAs inspectorG4dget said, this require every element to be
str
. A simple workaround would beprint '\n'.join(map(str, myList))
. -
jeromej over 11 years@inspectorG4dget Thank to notice, see my comment below for a workaround using
str.join
even without all elements beingstr
. -
Sergey Antopolskiy about 6 yearsthis should be accepted as correct answer, it is far better than doing a loop
-
Jigarius about 6 years@SergeyAntopolskiy I wonder if doing a loop is actually that bad. The loop just reads the values and outputs them. Whereas the join results in the creation of a new string in the memory containing all the values and then prints it out. That could result in a performance penalty for long lists IMO.
-
Sergey Antopolskiy about 6 years@JigarMehta you may have a point there. at least, this should be accepted as a correct answer, if not the correct answer