Contents
You already know that a list is a data structure that stores multiple elements or objects in a single variable. Let’s say you have a list and want to print it vertically, then how you will print it? In this tutorial, you will get to know the various methods to print a list vertically in Python.
Methods to print list vertically in Python
There are multiple approaches you can use to print a list vertically in Python. Here are common methods.
Method 1: Using a for loop and string join
def print_vertically(lst):
for item in lst:
print('\n'.join(str(item)))
# Example usage
my_list = [10, 20, 30, 40, 50]
print_vertically(my_list)
Output
10
20
30
40
50
Method 2: Using the * operator and the zip function
def print_vertically(lst):
print(*zip(*map(str, lst)), sep='\n')
# Example usage
my_list = [10, 20, 30, 40, 50]
print_vertically(my_list)
Output
10
20
30
40
50
Method 3: Using a for loop and nested list comprehension
def print_vertically(lst):
[print(x) for item in lst for x in str(item)]
# Example usage
my_list = [10, 20, 30, 40, 50]
print_vertically(my_list)
Output
10
20
30
40
50
Method 4: Using the join function with a newline character
def print_vertically(lst):
print('\n'.join(map(str, lst)))
# Example usage
my_list = [10, 20, 30, 40, 50]
print_vertically(my_list)
Output
10
20
30
40
50
Method 5: Using the * operator and the unpacking feature
def print_vertically(lst):
print(*[str(item) for item in lst], sep='\n')
# Example usage
my_list = [10, 20, 30, 40, 50]
print_vertically(my_list)
Output
10
20
30
40
50
Conclusion
In most cases, you will display the list horizontally. But for the knowledge, if you want to display the list vertically then the above methods will allow you to print. You can use any method you are comfortable with with the code.
Leave a Reply