Accessing elements inside tuple

This blog descries how to access elements inside tuple

There are two ways to access element inside a tuple either by using indexing or slicing

Example : Creating a tuple of numbers which includes 6 elements

tup = (1,2,3,4,5,6)

Index represent position number of each element
Index always start from 0
In the above tuple, first element will have index number 0, second element will have index number 1 and so on

Use index number 0 to print the first element from a tuple

print(tup[0])

Output

1

Similarly to print the second element from a tuple, use index number 1

print(tup[1])

Output

2

We can also use negative index for accessing elements from a tuple

Last element in a a tuple will have negative index -1, second last element will have -2 index number and so on

Consider a below example, where tuple is created with 6 elements and then using negative index -1 to access the last element

tup = (1,2,3,4,5,6)
print(tup[-1])

Output

6

In the same way, accessing second last element using negative index -2.

tup = (1,2,3,4,5,6)
print(tup[-2])

Output

5

Now using slicing to access element from a tuple. Slicing is use to extract some of the elements from a tuple. Slicing take below format

[start: stop: stepsize]

Start : Represent the start element
Stop : Represent the ending element
Stepsize : Represent incremental value

Below statement will print all elements from a tuple

tup = (1,2,3,4,5,6)
print(tup[:])

Output

(1, 2, 3, 4, 5, 6)

Below statement will print elements in the index position between 2 and 5

tup = (1,2,3,4,5,6)
print(tup[2:5])

Output

(3, 4, 5)

Printing alternate element

tup = (1,2,3,4,5,6)
print(tup[::2])

Ouput

(1, 3, 5)

Elements can be printed in alternate order from a reverse(right to left) using negative slicing

tup = (1,2,3,4,5,6)
print(tup[::-2])

Output

(6, 4, 2)

When slicing is specified in negative, elements are extracted from right to left.
For positive slicing, they are extracted from left to right

Extracted elements can be stored in a separate variable. Below is the example.

tup = (1,2,3,4,5,6)
v1,v2 = tup[2:4]
print(v1)
print(v2)

Output

3
4

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s