Skip to main content

Python tuple Accessing tuples

 

Python tuple Accessing tuples 

Accessing elements in a tuple in Python is similar to accessing elements in a list.  You          can use index notation to retrieve individual elements or use slicing to extract a subset of      elements. Here are some examples:


Accessing Individual Elements:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

# Accessing elements by index

print(my_tuple[0])  # Output: 1

print(my_tuple[3])  # Output: 'a'

 

Slicing:

You can use slicing to extract a range of elements from the tuple:

# Slicing

print(my_tuple[1:4])  # Output: (2, 3, 'a')

 

Negative Indexing:

You can use negative indexing to access elements from the end of the tuple:

# Negative indexing

print(my_tuple[-1])  # Output: 'c'

print(my_tuple[-2])  # Output: 'b'

 

Length of a Tuple:

You can use the len() function to get the length of a tuple:

# Length of a tuple

print(len(my_tuple))  # Output: 6

Comments