Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Printing a list vertically in Python
When working with lists in Python, sometimes you need to display elements vertically instead of the default horizontal format. This article explores three different approaches to print list elements in a vertical arrangement.
Basic List Structure
A Python list stores elements in square brackets and normally prints horizontally ?
fruits = ['apple', 'banana', 'cherry'] print(fruits)
['apple', 'banana', 'cherry']
Method 1: Using Simple For Loop
The most straightforward approach uses a for loop to print each element on a separate line ?
fruits = ['apple', 'banana', 'cherry']
for item in fruits:
print(item)
apple banana cherry
Printing Nested Lists Vertically
For nested lists, use nested loops to print all elements vertically ?
nested_data = [[20, 40, 50], [79, 80], ["Hello"]]
for sublist in nested_data:
for item in sublist:
print(f"[{item}]")
[20] [40] [50] [79] [80] [Hello]
Method 2: Using itertools.zip_longest()
The itertools.zip_longest() function handles lists of different lengths by filling missing values ?
import itertools
nested_data = [[20, 40, 50], [79, 80], ["Hello"]]
for row in itertools.zip_longest(*nested_data, fillvalue=" "):
if any(item != " " for item in row):
print(" ".join(str(item) for item in row))
20 79 Hello 40 80 50
Method 3: Using Class-Based Approach
You can encapsulate the vertical printing logic in a class for reusability ?
class VerticalPrinter:
def __init__(self, data):
self.data = data
def print_vertical(self):
for item in self.data:
print(f"\t{item}")
# Usage
numbers = ['20', '40', '50', '79', '80', "Hello"]
printer = VerticalPrinter(numbers)
printer.print_vertical()
20 40 50 79 80 Hello
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Simple for loop | O(n) | Basic vertical printing |
| itertools.zip_longest() | O(n) | Nested lists with different lengths |
| Class-based | O(n) | Reusable, organized code |
Conclusion
Use simple for loops for basic vertical printing. Choose itertools.zip_longest() for complex nested structures, and class-based approaches when you need reusable, organized code.
