Skip to main content

Python 3: Get First and Last element of a list

· 2 min read
Samuel Iheadindu

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.

# python 3 - using list index method
list = [1, 8, 6, 3, 4]
ext = [list[0], list[-1]]
print(str(ext))
Output:-> [1, 4]

Using list slicing method:

List slicing technique can be used to extract the first and last element of a list.

# python 3 - using list slicing method
list = [1, 8, 6, 3, 4]
ext = list[::len(list)-1]
print(str(ext))
Output:-> [1, 4]

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.

# python 3 - using list comprehension method
list = [1, 8, 6, 3, 4]
ext = [list[i] for i in (0,-1)]
print(str(ext))
Output:-> [1, 4]