How to get the last element from a tuple in Python?

Here we are to see how to get the last element from Tuple using Python as Programming Language. For this task, we need to understand the concept of Indexing.

Let’s understand this with an example.

i) Initially, a newborn child is 0 years old. After completion of 1 year, the age of the child will be 1 year and so on.
ii) Consider a building. Building starts with Ground (0) floor followed by 1st, 2nd floor and so on.

Similar is the concept of indexing. Indexing is accessing elements from sequence. Indexing in python is denoted with 0,1,2,.. or -1,-2,.. where 0 is the first index and -1 is the last index. In order to fetch element from sequence using Indexing “[ ]” is used.

tuple

Get the last element from Tuple

I) Using Negative Index

Step 1: Create a Tuple

The tuple is created on which Negative Indexing has to be implemented. A Tuple is capable of storing immutable objects. Immutable values refer to those values that can’t be changed.

Since we are learning how to display last element from tuple, first of all, create a tuple:

t = ("Codespeedy",3600,49.70,4,"Rani")
Step 2: Use Negative Index
The negative index starts from where the sequence ends. Here, index value of -1 gives last element, -2 give second last element and so on. Python supports Negative Indexing. Hence, in order to access last element from tuple we use index value of -1.
print("Last element is:",t[-1])

OUTPUT

Last element is: 'Rani'

Following is the pictorial representation of the entire process :

get last element from tuple in Python

II) Using len(seq)

Step 1: Create a Tuple

Let’s create our tuple:

t = ("Codespeedy",3600,49.70,4,"Rani")

Step 2: Use len(seq) 

len() calculates the total length of tuple. Using this value we can the index of last element. Since indexing in python starts with 0, index of last element will be (length of tuple)-1.

print("Last element is:",t[len(t)-1])

Following is the pictorial representation of the entire process :

tupple

Thank You.

You may also read: Getting a Random element from a Tuple in Python

One response to “How to get the last element from a tuple in Python?”

  1. Luis Fernando says:

    In this example, how do I print the last two values: 4,”Rani”

    I could not discover that.

    TX

Leave a Reply

Your email address will not be published. Required fields are marked *