In this tutorial, we will learn how to print the first and last elements of a list using Python. Lists are one of the versatile data structures in Python that makes it easy to perform various operations on elements.
Let’s dive into the steps for printing the first and last elements of a list in Python.
Step 1: Create a List
First, you need to create a list with some elements in it. We will use this list to print the first and last elements. Here’s an example:
1 |
my_list = [10, 20, 30, 40, 50] |
Step 2: Print the First Element
To print the first element of the list, you can use the index value 0. A list starts with index 0, as in most programming languages. To access the first element, just use the index inside square brackets like this:
1 2 |
first_element = my_list[0] print("First Element:", first_element) |
Step 3: Print the Last Element
To print the last element of the list, you can use the index value -1. Python supports negative indexing, which means you can start counting from the end of the list using negative numbers. To access the last element, use the index -1 inside square brackets like this:
1 2 |
last_element = my_list[-1] print("Last Element:", last_element) |
Step 4: Putting It All Together
Here is the complete Python code, combining all the steps above:
1 2 3 4 5 6 7 |
my_list = [10, 20, 30, 40, 50] first_element = my_list[0] print("First Element:", first_element) last_element = my_list[-1] print("Last Element:", last_element) |
Now, let’s execute the code and see the output:
First Element: 10 Last Element: 50
Full Code
1 2 3 4 5 6 7 |
my_list = [10, 20, 30, 40, 50] first_element = my_list[0] print("First Element:", first_element) last_element = my_list[-1] print("Last Element:", last_element) |
As you can see, the output displays the first and last elements of the list: 10 and 50, respectively.
Conclusion
In this tutorial, you learned how to print the first and last elements of a list using Python. This simple technique is helpful in many real-world applications like data extraction, manipulation, and analysis. Remember that you can always refer to the official Python documentation on lists for more information on list operations and functionalities.