You can extract first and last elements from a Python list and return the remaining elements in the following ways:
Using Slicing
You can extract the first and last elements by using their respective indexes and create a list for the rest of the elements by slicing from the second element to the second-to-last element, as shown in the following example:
my_list = [1, 2, 3, 4, 5]
first = my_list[0]
last = my_list[-1]
rest = my_list[1:-1]
print("first element:", first) # 1
print("last element:", last) # 5
print("remaining elements:", rest) # [2, 3, 4]
You can re-write this as a one-liner as well, for example, in the following way:
# ...
first, last, rest = my_list[0], my_list[-1], my_list[1:-1]
# ...
When you slice a list in Python, it is generally an efficient operation as it creates a new list that references the original list's elements without copying them. It simply creates a new view into the same memory space. This means slicing takes O(n)
time, where n
is the number of elements in the slice. It doesn't involve copying elements, which is advantageous for performance.
Using Extended Unpacking
In Python 3+, you can use extended unpacking with the *
operator to capture the middle elements (i.e. elements between the first and last elements) into the "rest
" list as shown in the following example:
# Python 3+
my_list = [1, 2, 3, 4, 5]
first, *rest, last = my_list
print("first element:", first) # 1
print("last element:", last) # 5
print("remaining elements:", rest) # [2, 3, 4]
When you use extended unpacking with the *
operator, it creates an intermediate list to hold the middle elements. In the worst case, this intermediate list could consume additional memory and time to construct. This overhead might be negligible for small lists but could become noticeable for larger lists.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.