48

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

user1825241
  • 846
  • 4
  • 9
  • 17

3 Answers3

129

Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:

from __future__ import print_function  # Py 2.6+; In Py 3k not needed

mylist = ['10', 12, '14']    # Note that 12 is an int

print(*mylist,sep='\n')

Prints:

10
12
14

Eventually, print as Python statement will go away... Might as well start to get used to it.

  • 1
    This answer is cool and its ease included in the usual print statement rather than in loops. – Rajesh Mappu Oct 09 '17 at 18:34
  • Brilliant! I never thought of unpacking a list in the context of `print()`. I've long wondered how to implement this in a simple way. Much prefer this to looping or calling `str` functions. – Karl Baker Feb 27 '19 at 01:41
  • why is the * necessary here before `mylist`? – Pstr Apr 12 '19 at 01:35
  • even if I removed `sep` parameter the items were being displayed in new lines. But removing `*` made list printing inline. Why so? – Verma Aman Jul 18 '19 at 08:37
  • 1
    @Pstr [Check this out](https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558) – Verma Aman Jul 18 '19 at 08:57
  • This should have been the accepted answer. Brilliant! +1 – harvpan Dec 04 '19 at 17:21
62

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 11
    As inspectorG4dget said, this require every element to be `str`. A simple workaround would be `print '\n'.join(map(str, myList))`. – jeromej Nov 18 '12 at 19:54
  • this should be accepted as correct answer, it is far better than doing a loop – Sergey Antopolskiy Mar 02 '18 at 11:37
  • 1
    @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. – Jigarius Mar 10 '18 at 02:07
  • @JigarMehta you may have a point there. at least, this should be accepted as *a* correct answer, if not *the* correct answer – Sergey Antopolskiy Mar 10 '18 at 14:03
40

You can just use a simple loop: -

>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
        print elem 

10
12
14
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525