In this tutorial, we are going to learn how to print a numbered list in Python. In programming, a common task that one may be faced with is creating and manipulating lists.
In Python, Lists are a versatile and powerful data type that allows you to store a collection of items. They are mutable, which means any value can be modified, added, or removed from the list, even after it has been created.
Step 1: Creating The List
Before you can print, you will create a numbered list. Lists in Python are simply declared by creating a variable and assigning comma-separated values between square brackets []
to it.
1 |
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'] |
Step 2: Print The List
To print the list you can simply use the Python print() function.
1 |
print(fruits) |
['apple', 'banana', 'cherry', 'date', 'elderberry']
Step 3: Print a Numbered List
For a better view, you can loop through the list with the help of an iteration control structure and print each item prefixed by its order number.
1 2 |
for i in range(len(fruits)): print(str(i + 1) + ". " + fruits[i]) |
1. apple 2. banana 3. cherry 4. date 5. elderberry
The Full Code
1 2 3 4 5 6 |
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'] print(fruits) for i in range(len(fruits)): print(str(i + 1) + ". " + fruits[i]) |
Conclusion
In this tutorial, we have seen how to print a numbered list in Python. This could be a useful tool to display data in an ordered, clear format.
Remember, that Python uses a zero-based index, so if you want to number your list starting at 1, you will need to add 1 to the index in your print statement.
Once you understand these basic concepts, you can further explore the Python data structures to enhance your programming skills.