get the first and last element of a list in Python

How to get the first and last element of a list in Python ?

This tutorial guides you on how to get the first element of a list and get the last element of a list in Python using numerous ways with examples.

Understand Slice Notation – Python

Before you learn how to get the first element of a list in Python, you should understand slice notation in Python.

As per Python documentation, you need to think that indices (both positive and negative indexes) are pointing between characters as depicted in the following diagram.

get the first and last element of a list in PythonNote, the first row in the above diagram indicates positive indexes position numbers from o to 6 for the string. And second row indicates the corresponding negative indexes. When you slice the string from index i to index j, it will consists of all the characters between i and j.

For more details and examples. Please check more details on Understand Slice Notation in Python.

get the first element of a list in Python

For instance, let’s consider my_list is the given input list.

my_list = [10, 20, 30, 40, 50, 11, 22, 33, 44, 55, 66, 77]

To get the first element of the given list, you can use starting index (positive) as shown below.

my_list[0]
10

By using length function and the negative index, you can find the first element of a list as shown below.

my_list[-len(my_list)]
10

Note, if length of any given list is zero, then you will get IndexError as shown below.

my_list=[]

If the length of the list is zero, you will get IndexError: list index out of range.

my_list[0]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-66-1ba9390cde38> in <module>
----> 1 my_list[0]

IndexError: list index out of range

get the last element of a list in Python

To get the last element of a list in Python, you can use starting negative index “-1” as shown below.

my_list[-1]
77

Similarly, to get the second to the last element of a list.

my_list[-2]
66

Note, you can use the negative index with the slice notation as shown below to get the last element.

my_list[-1:]
[77]

And, if length of list is zero in the above case.

my_list=[]

It wont crib IndexError, rather it will return empty list as shown below.

m_list[-1:]
[]

That’s it. You had learnt how to get the first element of a list and how to get last element of a list in Python in numerous ways.

Hope it is helpful πŸ™‚

You’ll also like:

References

Β 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments