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
Share:
182,816
user1825241
Author by

user1825241

Updated on July 09, 2022

Comments

  • user1825241
    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
    inspectorG4dget over 11 years
    This would actually work better than str.join which expects each element to be a str.
  • jeromej
    jeromej over 11 years
    As inspectorG4dget said, this require every element to be str. A simple workaround would be print '\n'.join(map(str, myList)).
  • jeromej
    jeromej over 11 years
    @inspectorG4dget Thank to notice, see my comment below for a workaround using str.join even without all elements being str.
  • Sergey Antopolskiy
    Sergey Antopolskiy about 6 years
    this should be accepted as correct answer, it is far better than doing a loop
  • Jigarius
    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
    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