5 Best Ways to Get First and Last Elements of a List in Python

5/5 - (1 vote)

πŸ’‘ Problem Formulation: When working with lists in Python, a common requirement is to retrieve the first and the last elements. Let’s say you have a list items = [ "apple", "banana", "cherry", "date", "elderberry" ] and you want to specifically access “apple” and “elderberry” efficiently. This article demonstrates five different methods to achieve that.

Method 1: Using Indexing

Indexing is the simplest method to access elements in a list. In Python, you can directly get the first element with index 0 and the last element with index -1. This method is very fast and efficient because accessing an item by index is done in constant time.

Here’s an example:

items = ["apple", "banana", "cherry", "date", "elderberry"]
first_item = items[0]
last_item = items[-1]
print(first_item, last_item)

Output:

apple elderberry

This code snippet shows how you can easily grab the first and last items of the list items using indexing, where items[0] gives you the first element, and items[-1] gives you the last element of the list.

Method 2: Using the list.pop() Method

The pop() method removes and returns the element at a given index. Using pop(0) for the first, and pop(-1) for the last element, you can retrieve the desired items. It is important to note that this method modifies the original list.

Here’s an example:

items = ["apple", "banana", "cherry", "date", "elderberry"]
first_item = items.pop(0)
last_item = items.pop(-1)
print(first_item, last_item)

Output:

apple elderberry

This code uses the pop() method to remove the first and last items from the list and then prints them out. Remember that after executing this code, the list items will have two elements less as the items have been popped out.

Method 3: Slicing the List

List slicing in Python can be used to retrieve several elements from a list at once. By using the slice [:1] and [-1:], you can create new lists that contain only the first and last elements correspondingly. This method does not modify the original list.

Here’s an example:

items = ["apple", "banana", "cherry", "date", "elderberry"]
first_item = items[:1]
last_item = items[-1:]
print(first_item, last_item)

Output:

['apple'] ['elderberry']

In this snippet, list slicing is used to get the first and the last elements. Unlike indexing, slicing returns a new list. So the output is a pair of lists, each containing one element.

Method 4: Unpacking Sequences

Python allows us to unpack sequences directly into variables. If you know that a list has more than one item, you can unpack the first and last items directly into variables. This is best suited to situations where the number of variables on the left-hand side matches the length of the sequence.

Here’s an example:

items = ["apple", "banana", "cherry", "date", "elderberry"]
first_item, *_, last_item = items
print(first_item, last_item)

Output:

apple elderberry

This clever use of unpacking with an asterisk allows us to ignore the middle elements of the list and directly assign the first and last items to the first_item and last_item variables.

Bonus One-Liner Method 5: Using Tuple Conversion

By converting a list into a tuple, you can apply multiple index accessing in a one-liner. This is a concise and pythonic way to get both items simultaneously and is particularly useful when working with fixed-size lists.

Here’s an example:

items = ["apple", "banana", "cherry", "date", "elderberry"]
first_item, last_item = (items[0], items[-1])
print(first_item, last_item)

Output:

apple elderberry

This one-liner creates a tuple from the first and last items of the list and unpacks them back into the variables first_item and last_item.

Summary/Discussion

  • Method 1: Indexing. Straightforward and efficient. Best when you want to access elements without modifying the list.
  • Method 2: list.pop() Method. Simple, but alters the original list. Use it if you need to remove these elements as part of the operation.
  • Method 3: Slicing the List. Non-destructive and provides a new list with the selected items. Ideal when you need to keep the original list intact.
  • Method 4: Unpacking Sequences. Modern and clean, but not suitable for lists with unknown or large sizes as it could lead to value waste or errors.
  • Method 5: Using Tuple Conversion. Concise one-liner suitable for small or fixed-size lists.