How to get the First and Last Element of a List in python with example

A list is a data structure to store the collection of elements in the insertion order.

This tutorial explains about following things in Python with examples

  • How to get the First object from a List
  • How to get the Last Element from a List
  • How to get any position element from a List. Elements in a List always start with index=0 to index=len(list)-1.

For example, the first element index is zero, Last element index is the length of a list minus 1.

How to get element from a List

Elements from a List can be retrieved using list[index] syntax. Here is an example

list = [1, 2, 3,4,5,6,7,8,9]

print(list[0]) #1
print(list[1]) #2
print(list[2]) #3
print(list[3]) #4

if the index is more than the given length of a list, It throws IndexError: list index out of range. In the following list, the Index is passed as 10, greater than len(list)-1, Hence it gives an error.

list = [1, 2, 3,4,5,6,7,8,9]
print(list[10]) # throws IndexError

Output:

Traceback (most recent call last):
File "main.py", line 8, in <module>
print(list[len(list)])
IndexError: list index out of range

How to get the First and Last elements of a List from the beginning in Python

You can use an index with positive values from zero to up to a length of a list, for the beginning of a list.

use list[0] for getting the first element from a list.

list = [1, 2, 3,4,5,6,7,8,9]

print(list[0]) #1

In case of Last element, use list[len(list)-1].

list = [1, 2, 3,4,5,6,7,8,9]
print(list[len(list)-1]) #9

Another syntax to return a list with indexed value i.e list[:index]

list = [1, 2, 3,4,5,6,7,8,9]

print(list[:1]) #[1]

How to get the First and Last element of a List from End in Python

This example retrieves an index from the end of a list

You can use an index with negative values from -1 up to a length of a list-1 with a minus, for the End of a list.

use list[-1] for getting the last element from a list. use list[-2] for getting the second last element from a list.

list = [1, 2, 3,4,5,6,7,8,9]

print(list[-1]) #9
print(list[-2]) #8

if you pass a negative index equal or greater than the length of a list, It throws IndexError: list index out of range

list = [1, 2, 3,4,5,6,7,8,9]
print(list[-10]) # IndexError: list index out of range

Output:

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(list[-10]) #8
IndexError: list index out of range

In case of Last element, use list[len(list)-1].

list = [1, 2, 3,4,5,6,7,8,9]
print(list[len(list)-1]) #9

Another way, is to return the sublist by subtracting indexed value

list = [1, 2, 3,4,5,6,7,8,9]

print(list[:-1]) #[1]

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Conclusion

Learned multiple ways to return List with first, last with positive and negative indexes.