Samuel Iheadindu
Software Engineer. Web Developer. Systems Analyst
Python 3: Get First and Last element of a list
Different methods to extract the first and last elements from a list in Python, including index access, slicing, and list comprehension.
Sometimes, you are presented with a list in python, and you will like to get the first and last elements of the list. In other programming languages like JavaScript (es6), you have feature called destructuring for unpacking a list of items.
However, there are several ways this can be accomplished in Python and we will discuss some of the options below:
Using list index method:
Using the indices of the list, we can perform this task. However, this is a naive method to achieve this task.
Using list slicing method:
List slicing technique can be used to extract the first and last element of a list.
Using list comprehension method:
List comprehension can be employed to provide a shorthand to the loop technique to find first and last element of the list. Naive method of finding is converted to a single line using this method.