Python - Print List as Lines
Python - Print List as Lines
To print the list as lines in Python, i.e., print each element of the list in a new line, use a For loop to iterate over the list, and print each element in a new line. Or you can join the list elements with new line as a separator using string join() method, and print the resulting string.
For example, consider the following list.
x = ['apple', 'banana', 'cherry']
We have to print this list as lines to console output as shown in the following.
apple
banana
cherry
In this tutorial, we shall go through some examples where we take a list of elements, and print the elements in the list in lines to the standard console output.
1. Print list as lines using For loop in Python
Consider that we are given a list in x, and we have to print the elements in this list as lines using For loop statement.
Steps
- Given a list in x.
- Write a For loop that iterates over x.
- During each iteration, print the element to output using print() built-in function. By default print() function prints each element in a new line.
Program
The complete program to print a list as lines using For loop.
Python Program
x = ['apple', 'banana', 'cherry']
for element in x:
print(element)
Output
apple
banana
cherry
The elements in list are printed each in a new line.
2. Print list as lines using String join() method in Python
Consider that we are given a list in x, and we have to print the elements in this list as lines using String join() method.
Steps
- Given a list in x.
- Join the elements in x with new line as a separator using string join() method. Call join() method on new line
"\n"
taken in a string, and pass the list x as argument to the method.
"\n".join(x)
- join() method returns a string where all the elements in the list are joined by the specified new line. Assign it to a variable, say lines, and print it to console output using print() built-in function.
Program
The complete program to print a list as lines using String join() method.
Python Program
x = ['apple', 'banana', 'cherry']
lines = "\n".join(x)
print(lines)
Output
apple
banana
cherry
Summary
In this tutorial, we have seen how to print list elements as lines using For loop or String join() method, with well detailed examples.