Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print list elements line by line - is it possible using format

I very like quite new Python convention to print things with .format()

Is it possible using it to print element line by line. Assuming of course number of elements is unknown.

Working example will be appreciated.

like image 780
andilabs Avatar asked Mar 27 '14 17:03

andilabs


People also ask

How do I print a list of elements in separate lines?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print a list and a string on the same line?

To print a list and display it in a single line, a straightforward solution is to iterate over each element in a for loop and print this element into the same line using the print() function with the end=' ' argument set to the empty space.


1 Answers

If you are using Python 3.x and your intention is to just printing the list of elements, one in each line, then you can use print function itself, like this

my_list = [1, 2, 3, 4]
print(*my_list, sep="\n")

*my_list simply unpacks the list elements and pass each one of them as parameters to the print function (Yes, print is a function in Python 3.x).

Output

1
2
3
4

If you are using Python 2.x, then you can just import the print function from the future like this

from __future__ import print_function

Note: This import should be the first line in the file.

like image 130
thefourtheye Avatar answered Sep 18 '22 20:09

thefourtheye