w3resource

Python Exercise: Get an item of a tuple


7. Get the 4th Element from the Last Element of a Tuple

Write a Python program to get the 4th element from the last element of a tuple.

Visual Presentation:

Python Tuple: Get an item of a tuple.

Sample Solution:

Python Code:

# Create a tuple containing a sequence of items
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
# Print the contents of the 'tuplex' tuple
print(tuplex)

# Get the 4th element of the tuple (index 3)
item = tuplex[3]
# Print the value of the 'item'
print(item)

# Get the 4th element from the end of the tuple (index -4)
item1 = tuplex[-4]
# Print the value of the 'item1'
print(item1) 

Sample Output:

('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')                                                              
e                                                                                                             
u

Flowchart:

Flowchart: Get an item of a tuple

For more Practice: Solve these Related Problems:

  • Write a Python program to retrieve the 4th element from the end of a tuple using negative indexing.
  • Write a Python program to implement a function that returns the element located 4 positions from the last element of a tuple.
  • Write a Python program to check if a tuple is long enough and then print its 4th element from the end; otherwise, print an error message.
  • Write a Python program to use slicing to obtain the 4th element from the last element of a tuple and output it.

Python Code Editor:

Previous: Write a Python program to convert a tuple to a string.
Next: Write a Python program to create the colon of a tuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.