How to get the first and last element from the List
How to get the first and last element from the List
30821-Aug-2023
Updated on 23-Aug-2023
Home / DeveloperSection / Forums / How to get the first and last element from the List
How to get the first and last element from the List
Aryan Kumar
23-Aug-2023Sure, there are a few ways to get the first and last element from a list in Python.
Here are two ways to get the first and last element from a list:
list.index()
method:Python
In this example, the
list
variable is a list that has the values 1, 2, 3, 4, and 5. Thelist.index()
method returns the index of the element in the list. Thefirst_element
variable is assigned the value of the first element in the list, which is 1. Thelast_element
variable is assigned the value of the last element in the list, which is 5.list[0]
andlist[-1]
syntax:Python
In this example, the
list
variable is a list that has the values 1, 2, 3, 4, and 5. Thelist[0]
syntax returns the first element in the list, which is 1. Thelist[-1]
syntax returns the last element in the list, which is 5.Which method you use depends on your specific needs. If you need to get the first and last element and you don't need to do any further processing on the elements, then the
list.index()
method is a good option. If you need to do further processing on the elements, then thelist[0]
andlist[-1]
syntax is a good option.