Rendering lists in Python horizontally is easy and frequently done, but there are instances when you would want to display a list vertically.
This short tutorial will guide you on how to display a list vertically in Python. This may come in handy when handling large lists where horizontal scrolling becomes a nightmare. Follow the steps below to achieve this in no time.
STEP 1: Create a List
First, we need to create a list to work with. A list in Python is a sequence of elements enclosed in square brackets([]), separated by commas. Below is a simple method to create a list in Python:
1 2 3 |
#Creating a list animals = ['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger'] |
STEP 2: Loop Through the List Items
Next, we will use a basic for loop to iterate over our previously created list. The for loop helps us to go through each element in the list one after the other:
1 2 3 4 |
#Looping through the list items for animal in animals: print(animal) |
This will still print the items horizontally. How then do we print our list vertically?
STEP 3: Display List Vertically
To render our list vertically, we print each list item on a new line. Python’s print function has an implicit newline. Using a for loop, each list item is printed independently on a new line, thus making our list appear vertically:
1 2 3 4 |
#Displaying list vertically for animal in animals: print(animal) |
Final Python Code
The full code should look like this:
1 2 3 4 5 6 |
#Creating a list animals = ['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger'] #Displaying list vertically for animal in animals: print(animal) |
The output of the Final Code
When you run the above code, the output should appear like this
Cat Dog Elephant Lion Tiger
Conclusion
In this tutorial, we learned how to display a list vertically using Python’s for loop and print functions. We hope this tutorial helps you in your future Python coding. If you have any questions, feel free to drop them in the comment section below.