Python, as one of the most popular programming languages, offers a wide array of functions that are instrumental in data manipulation and organization. One of these core functionalities is the ability to create a numbered list.
Python essentially handles the heavy lifting part for you. In this tutorial, we will illustrate how to print a numbered list in Python.
Step 1: Create Your List
Before anything else, you need to create the list of items that you want to number. Let’s create a simple list of names:
1 |
names = ["John", "Mary", "Peter"] |
The above code creates a list of three names. These are the names we will number in this tutorial.
Step 2: Using the Enumerate Function
The enumerate() function in Python is used for creating numbered lists. Do this by using a for loop in conjunction with the enumerate function, as shown in the following example:
1 2 |
for i, name in enumerate(names, 1): print(i, name) |
What this code does is to loop through each item in the list (name) along with its index (i), starting from 1. Each item and its respective index are then printed out to the console.
Step 3: Understanding the Output
When the above code is run, it will produce the following output:
1 John 2 Mary 3 Peter
The output is a numbered list of names from the initial list.
What you need to remember:
The enumerate() function is a built-in Python function that makes creating a numbered list quick and efficient. The second parameter in the enumerate() function, in our case set to 1, determines the start number of the enumeration.
Full Code
Below is the full code we have just developed:
1 2 3 4 |
names = ["John", "Mary", "Peter"] for i, name in enumerate(names, 1): print(i, name) |
1 John 2 Mary 3 Peter
Conclusion
As demonstrated, creating a numbered list in Python is relatively straightforward thanks to its built-in enumerate() function. Remember that Python offers an efficient means of manipulating lists that help reduce the complexity of your code. If you have any questions, feel free to leave a comment below.