Open In App

Get first and last elements of a list in Python

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of getting the first and last elements of a list in Python involves retrieving the initial and final values from a given list. For example, given a list [1, 5, 6, 7, 4], the first element is 1 and the last element is 4, resulting in [1, 4].

Using indexing

This is the most straightforward way to get the first and last elements. We can access the first element with a[0] and the last element with a[-1]. It is quick and easy to understand, making it the most commonly used approach.

Python
a = [1, 5, 6, 7, 4]

res = [a[0], a[-1]]
print(res)

Output
[1, 4]

Explanation:[a[0], a[-1]] creates a new list res containing the first element of a (accessed by a[0]) and the last element of a (accessed by a[-1]).

Using unpacking

Unpacking allows us to extract the first and last elements while ignoring the rest. Using first, *_, last = a gives the first and last elements directly. It is cleaner when we only care about the ends and don’t need the elements in between.

Python
a = [1, 5, 6, 7, 4]

first, *_, last = a

res = [first, last]
print(res)

Output
[1, 4]

Explanation: first, *_, last = a assigns the first element (1) to first, the last element (4) to last, and the middle elements [5, 6, 7] to _, which is ignored as _ is a placeholder for unused values. Then, res = [first, last] creates a new list [1, 4].

Using list comprehension

List comprehension can be used to pick specific positions from a list. You can get the first and last elements using [a[i] for i in (0, -1)]. This method works well but is less readable compared to indexing.

Python
a = [1, 5, 6, 7, 4]

res = [a[i] for i in (0, -1)]
print(res)

Output
[1, 4]

Explanation:[a[i] for i in (0, -1)] create a new list by accessing a[0] (first element 1) and a[-1] (last element 4), resulting in [1, 4], which is stored in res.

Using operator.itemgetter

itemgetter() function from the operator module fetches elements by index. We can get the first and last elements using itemgetter(0, -1)(a). It is useful when we need multiple elements by position, but less common for just two values.

Python
from operator import itemgetter

a = [1, 5, 6, 7, 4]

getter = itemgetter(0, -1)
res = list(getter(a))
print(res)

Output
[1, 4]

Explanation: itemgetter(0, -1) creates a getter function to fetch the first (a[0] → 1) and last (a[-1] → 4) elements from a. getter(a) extracts these values and list() converts them into [1, 4], stored in res.


Get First and Last Elements of a List in Python Program
Practice Tags :

Similar Reads