Accessing Tuple Elements Python

Accessing Tuple Elements Python

Now, we are quite familiar with what are some of the different ways to create tuples in our python programs. Now, Let’s have a look at how we can access the tuple elements. The thing is that the tuple items are ordered, unchangeable, and also allow duplicate values. The tuple items are indexed, which simply means that we can access the tuple items using the indexes. The indexing starts from 0, which means that the first tuple element has the index 0, the next element has 1, and so on.

So, with the help of indexes, we can access the tuple elements. Let’s have a look at a simple program, which demonstrates to us about accessing the elements of the tuple.

Accessing Tuple Elements Python

As you can see, we have a simple list in the above program and then we are trying to access the individual elements. Accessing the element is very simple. We just have to write the reference variable name, and then the square brackets, and within the square brackets, we give the index of that element, which we want to access. This is similar to how we access the individual elements from the list.

Again, here as well, if we are giving such an index, which is out of range for our tuple, then we are going to get into an error. Let’s have a look at the below program, which tries to demonstrate the same.

As you can see, we have a simple tuple, and then we are trying to access different individual elements from the tuple. In the last print line, we are trying to access the element from the index 20, which is simply out of range. So here, we are going to get into an error. You can try executing the program and observe the output as well. So here as well, if you are trying to access some index, which is out of range, you would get an error.

Here as well, we can make use of the negative indexing, to access the individual elements. Here, the index of -1 represents the last element, -2 index represents the second last element, and so on. So, whenever we require to access some last element from the tuple, but we do not want to calculate the length of the tuple, we can directly do it with negative indexing. Let’s have a look at a simple program, which demonstrates accessing the individual elements with the negative indexing.

As you can see in the above program, we are trying to access the individual tuple elements with negative indexing. You can try executing the above program and have a look at the output as well. So, whenever you need, you can try the negative indexing, to access individual elements.