Python - Print List as Column


Python - Print List as Column

To print the list elements as a column in Python, 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 column string.

Python - Print List as Column

For example, consider the following list.

x = ['apple', 'banana', 'cherry']

We have to print this list as column 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 column format to the standard console output.

1. Print list as column 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 a column using For loop statement.

Steps

  1. Given a list in x.
  2. Write a For loop that iterates over x.
  3. 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 column 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 as a column.

2. Print list as column 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 a column using String join() method.

Steps

  1. Given a list in x.
  2. 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)
  1. 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 column_string, and print it to console output using print() built-in function.

Program

The complete program to print a list as column using String join() method.

Python Program

x = ['apple', 'banana', 'cherry']

column_string = "\n".join(x)

print(column_string)

Output

apple
banana
cherry

Summary

In this tutorial, we have seen how to print list elements as a column using For loop or String join() method, with well detailed examples.