Accessing Tuple Elements
Elements in a tuple can be accessed using indexing and slicing, similar to lists. Indices start at 0
for the first element and can be negative for indexing from the end.
Indexing
Example 1: Accessing Elements by Positive Index
# Accessing tuple elements using positive index
tuple_data = ("Karthick AG", "Durai", "Vijay", "John", "Praveen", "Williams")
first_element = tuple_data[0]
third_element = tuple_data[2]
print("First Element:", first_element)
print("Third Element:", third_element)
Output
First Element: Karthick AG
Third Element: Vijay
Example 2: Accessing Elements by Negative Index
# Accessing tuple elements using negative index
last_element = tuple_data[-1]
second_last_element = tuple_data[-2]
print("Last Element:", last_element)
print("Second Last Element:", second_last_element)
Output
Last Element: Williams
Second Last Element: Praveen
Slicing
Example 3: Slicing a Tuple
# Slicing a tuple
sub_tuple1 = tuple_data[1:4]
sub_tuple2 = tuple_data[:3]
sub_tuple3 = tuple_data[3:]
print("Sub Tuple 1:", sub_tuple1)
print("Sub Tuple 2:", sub_tuple2)
print("Sub Tuple 3:", sub_tuple3)
Output
Sub Tuple 1: ('Durai', 'Vijay', 'John')
Sub Tuple 2: ('Karthick AG', 'Durai', 'Vijay')
Sub Tuple 3: ('John', 'Praveen', 'Williams')
Example 4: Slicing with Step
# Slicing with a step
every_other = tuple_data[::2]
reverse_tuple = tuple_data[::-1]
print("Every Other Element:", every_other)
print("Reversed Tuple:", reverse_tuple)
Output
Every Other Element: ('Karthick AG', 'Vijay', 'Praveen')
Reversed Tuple: ('Williams', 'Praveen', 'John', 'Vijay', 'Durai', 'Karthick AG')
Explanation: Slicing allows you to extract a subset of the tuple. By specifying a step, you can skip elements or reverse the tuple. Negative steps reverse the order.