Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

How to Get the First and Last Elements of a Python List?

First And Last Element

Sequence data is the most common form of data available. A Python list is the most commonly used way of storing sequence data in python.

Reading the First and Last Elements of a Python List

Elements in a list are numbered zero onwards. In this tutorial, we will learn different ways to access the first and the last elements from a list.

Let’s start by initializing a list.

1. Initialize a Python list

To initialize a list in Python use:

a = [6, 5, 9, 7]

This will initialize a new list ‘a‘ with the four elements we have mentioned.

2. Accessing list elements

You can access elements from the list by using the name of the list along with an index number. To print the first element use:

print(a[0])

To print the last element use :

print(a[-1])

Using -1 as the index gives us the last element from the list.

Python Code to Get First and Last Element of a List

The complete code is as follows :

a = [6, 5, 9, 7]
print("first element is" ,a[0])
print("last element is", a[-1])

Output

First And Last Element

Using Slicing to Retrieve First and Last Elements

To access the first and the last elements of the list using slicing use the following line of code:

ans = a[::len(a)-1]

This will store the first and the last elements to the ans variable.

Code to slice a Python list

a = [6, 5, 9, 7]
ans = a[::len(a)-1]
print ("The first and last elements of the list are : " + str(ans))
Output
Output

Get the first element of each tuple in a list

This case is a little different from the example above. Here we have a tuple as an element of the list. A list of tuples looks like :

[("a", "b", "c"), ("c", "d", "e"), ("f","g","h")]

We have to get the first element of each tuple.

Thanks to Python, we can do this using just one line of code using list comprehension.

first_tuple_elements = [a_tuple[0] for a_tuple in tuple_list]

This will create a list of all the first elements of the tuple. To get the last elements of all tuples replace 0 with -1.

first_tuple_elements = [a_tuple[-1] for a_tuple in tuple_list]

This will create a list with all the last elements of the tuples.

Retrieve First and Last Element of Tuples in a List

The complete code is as follows:

tuple_list = [("a", "b", "c"),("c", "d", "e"), ("f","g","h")]
first_tuple_elements = [a_tuple[0] for a_tuple in tuple_list]
print(first_tuple_elements)
Tuple Output

To get the last elements from all tuples :

tuple_list = [("a", "b", "c"),("c", "d", "e"), ("f","g","h")]
first_tuple_elements = [a_tuple[-1] for a_tuple in tuple_list]
print(first_tuple_elements)

Conclusion

This tutorial was about getting the first and the last element from a list in Python.